general backbone/marionette program structure - javascript

I need some general guidelines on how to structure a backbone/marionette application. Im very new to these frameworks and also to js in general.
Basically I have two pages and each page has a list. I have set up an application and a router for the application:
var app = new Backbone.Marionette.Application();
app.module('Router', function(module, App, Backbone, Marionette, $, _){
module.AppLayoutView = Marionette.Layout.extend({
tagName: 'div',
id: 'AppLayoutView',
template: 'layout.html',
regions: {
'contentRegion' : '.main'
},
initialize: function() {
this.initRouter();
},
...
});
module.addInitializer(function() {
var layout = new module.AppLayoutView();
app.appRegion.show(layout);
});
});
In the initRouter I have two functions, one for each page that gets called by router depending on the url.
The function for the content management page looks like this:
onCMNavigated: function(id) {
var cMModule = App.module("com");
var cM = new cMModule.ContentManagement({id: id, region: this.contentRegion});
contentManagement.show();
this.$el.find('.nav-item.active').removeClass('active');
this.cM.addClass('active');
}
So if this is called, I create a new instance of ContentManagement model. In this model, when show() is called, I fetch the data from a rest api, and I parse out an array of banners that need to be shown in a list view. Is that ok? The model looks like the following:
cm.ContentManagement = Backbone.Model.extend({
initialize: function (options) {
this.id = options.id;
this.region = options.region;
},
show: function() {
var dSPage = new DSPage({id: this.id});
dSPage.bind('change', function (model, response) {
var view = new cm.ContentManagementLayoutView();
this.region.show(view);
}, this);
dSPage.fetch({
success: function(model, response) {
// Parse list of banners and for each create a banner model
}
}
});
cm.ContentManagementLayoutView = Marionette.Layout.extend({
tagName: 'div',
id: 'CMLayoutView',
className: 'contentLayout',
template: 'contentmanagement.html',
regions: {
'contentRegion' : '#banner-list'
}
});
Now my biggest doubt is how do I go on from here to show the banner list? I have created a collectionview and item view for the banner list, but is this program structure correct?

do You really need marionnete to manage your application ? especially You are beginner as me too :)
try pure backbone first. You can still use marionette as a library.
backbone MVC architecture is described perfectly on many sites.

Related

Using tagName and className properties on Backbone View Vs using template

I have a Backbone View that is using a Backbone Collection to pull data from an api:
var HousesView = Backbone.View.extend({
initialize: function() {
this.collection = new Houses();
var that = this;
this.collection.fetch({
data: {
pageSize: 50
},
success: function () {
that.render();
},
error: function () {
console.error('There was an error in fetch');
}
});
},
tagName: 'section',
template: Handlebars.getTemplate('houses'),
render: function() {
this.$el.html(this.template({ houses : this.collection.toJSON() }));
return this;
}
});
It then creates models from the json pulled from the api and passes that as a collection to my template which takes each model and for e.g.just outputs the name attribute of that model as a list. That works fine.
My question is: because I am using a template to parse the data from this.collection.toJSON() the tagName I set on HouseView doesn't seem to be output in the html. If I am using a template for a View does this mean properties like tagName, className etc wont be output?
Also, ideally I would like to create a HouseView for each model from the collection and then display all of those in a wrapper HousesView.
In your example you are using custom rendered. In that case the auto generation of view from tagName, className and id will be spiked (overwrites by method this.$el.html in render function.).
The best approach is as you mentioned to create separate view and append it in render of main view to html.

Multiple times rendered collection in Backbone app

In my ongoing self thought process by building my simple blog app I am finding solutions to problems and encountering new ones.
Now successfully routing to a second view from a first one, and page is populated by the new views html.
Successfully save to the db new posts from second view, which is a form to add new posts.
First problem is:
In the first view I have the posts rendered five times, in order. There is not any js console messages. I have saved those posts each only one time from the second view, which is my postformview for saving posts.
Second problem is: From second view to the first view when navigated with the browser back button no posts rendered into page only the headers etc in one of the templates of this page is rendered.
What can be the issue here which I miss?
first view:
var postsListView = Backbone.View.extend({
collection: new postsCollection(),//! The Collection may be created to use in view. with new Coolectionname(). SOLVED it must be created, this attr is not suffcent and is not crating it.
template1: _.template( $('#postsListTemplate').html() ),//!!!Once forgot .html().
template2: _.template( $('#postsListItemTemplate').html() ),
initialize: function(){
this.collection.fetch();
this.collection.on('add', this.renderPostsListItem, this);
},
render: function(){
this.$el.html( this.template1() );//!this.el or this.$el. (each) or (each.toJSON()). SOLVED: use this.$el alongside el: a string, without $().
return this;
//* return this in every views render: if you want to chain el to render() of the view, for example in router while pcaing the rendered views el into DOM.
},
renderPostsListItem: function(){
console.log("view method renderPostsListItem have been reached.");
this.ul = 'ul';
this.collection.forEach(function(each){
$(this.ul).append( this.template2( each.attributes ) );
}, this);
return this;
},
events: {
"click a": 'toPostFormRoute'
},
toPostFormRoute: function(e){
console.log("view method toPostFormRoute have been reached.");
e.preventDefault();
Backbone.history.navigate( '/posts/postform' , {trigger: true});
console.log("view method toPostFormRoute have been reached.");
}
});
router:
//Define Client-Side Routes
var appRouter = Backbone.Router.extend({
el: 'body',
routes: {
'posts/postform': 'viewPostForm',
'': 'viewPosts'
},
viewPosts: function(){
console.log("router method viewPosts have been reached.");
this.postslistview = new postsListView();
$(this.el).html( this.postslistview.render().el );
},
viewPostForm: function(){
console.log("router method viewPostForm have been reached.");
this.postformview = new postFormView();
$(this.el).html( this.postformview.render().el );
}
});
UPDATE: Variation. adding each model when an add event fired y passing the model added to the method and rendering template only with it, appending only it. not iterating through collection them all.
This solves first issue but not the second issue. What can be the specific issue for this?
code fragment from the first view:
initialize: function(){
this.collection.fetch();
this.collection.on('add', this.renderPostsListItem, this);
},
renderPostsListItem: function(model){
console.log("view method renderPostsListItem have been reached.");
this.$el.find('ul').append( this.template2(model.toJSON()) );
return this;
},
Issue :
When a new item/model is added to the collection, all the items present in the collection are rendered/appended to the view's EL instead of only the newly added.
Root Cause :
renderPostsListItem#3
Solution
renderPostsListItem: function(model){
console.log("view method renderPostsListItem have been reached.");
this.collection.forEach(function(each){
this.$el.find('ul').append( this.template2(model.toJSON()) );
}, this);
return this;
},
http://backbonejs.org/#Collection-add

Giving a single reference to multiple Backbone.Models

I have a Backbone.Model which looks something like:
var FooModel = Backbone.Model.extend({
defaults: {
details: '',
operatingSystem: ''
};
});
There are many instances of FooModel which are stored in a collection:
var FooCollection = Backbone.Collection.extend({
model: FooModel
});
FooModel's OperatingSystem is a property which only needs to be calculated once and is derived asynchronously. For example:
chrome.runtime.getPlatformInfo(function(platformInfo){
console.log("Operating System: ", platformInfo.os);
});
If I perform this logic at the FooModel level then I will need to perform the logic every time I instantiate a FooModel. So, I think that this operation should be performed at a higher level. However, it is bad practice to give properties to a Backbone.Collection.
As such, this leaves me thinking that I need a parent model:
var FooParentModel = Backbone.Model.extend({
defaults: {
platformInfo: '',
fooCollection: new FooCollection()
},
initialize: function() {
chrome.runtime.getPlatformInfo(function(platformInfo){
this.set('platformInfo', platformInfo);
}.bind(this));
},
// TODO: This will work incorrectly if ran before getPlatformInfo's callback
createFoo: function(){
this.get('fooCollection').create({
details: 'hello, world',
operatingSystem: this.get('platformDetails').os
});
}
});
This works and is semantically correct, but feels over-engineered. The extra layer of abstraction feels unwarranted.
Is this the appropriate way to go about giving a property to a model?
Although Backbone Collections may not have attributes, they may have properties (as well as any object) which you can use to store shared data.
var FooCollection = Backbone.Collection.extend({
model: FooModel
initialize: function() {
this.platformInfo = null; // shared data
chrome.runtime.getPlatformInfo(function(platformInfo){
this.platformInfo = platformInfo;
}.bind(this));
},
// wrapper to create a new model within the collection
createFoo: function(details) {
this.create({
details: details,
operatingSystem: this.platformInfo? this.platformInfo.os : ''
});
}});
});

best way to realize backbone list application

I use backbone.boilerplate for creating a simple application.
I want to create module that can show collections of sites. Each sites has id and title attributes (example [{ id: 1, title: "github.com" }, { id: 2, title: "facebook.com" }].
My router:
routes: {
"": "index",
"sites": "sites"
},
sites: function () {
require(['modules/sites'], function (Sites) {
var layout = new Sites.Views.Layout();
app.layout.setView('#content', layout);
});
}
So, my sites module has layout, which do this:
Sites.Views.Layout = Backbone.Layout.extend({
template: "sites/layout",
className: 'container-fluid',
initialize: function () {
_.bindAll(this);
this.collection = new Sites.Collections.Sites();
this.collection.fetch({
success: this.render
});
},
beforeRender: function () {
var siteList = new Sites.Views.SiteList({
collection: this.collection
});
this.setView('.content', siteList);
},
});
Sites.Views.SiteList = Backbone.View.extend({
template: 'sites/list',
beforeRender: function () {
this.collection.each(function (model) {
var view = new Sites.Views.SiteItem({
model: model
});
this.insertView('tbody', view);
}, this);
}
});
Sites.Views.SiteItem = Backbone.View.extend({
template: 'sites/item',
tagName: 'tr',
serialize: function () {
return {
title: this.model.get('title')
};
}
});
ok. and now my question: help me please to choose best way to render one site view when user click on element of collection. I want that it is works like gmail: one screen for all letters and all screen for one letter when it choosed. Maybe you have link with example of similar application. I am waiting for your advices.
Looking at your pastebin code it seems like you have a basic understanding of Backbone, which is certainly all you need to get started.
That being said, you might find this article/tutorial helpful. It walks through the process of building inter-connected views (in the tutorial they are related <select> elements) which use AJAX to update their values:
http://blog.shinetech.com/2011/07/25/cascading-select-boxes-with-backbone-js/

Backbone.js - how to handle "login"?

Hi I'm trying to wrap my head around backbone.js for some days now but since this is my first MVC Framework, it's pretty hard.
I can easily get my Collections to work, fetching data from the server etc, but it all depends on first "logging" in per API-Key. I just don't know how to model this with a good MVC approach. (btw: I can't use the Router/Controller because it's a Chrome Extension)
The Flow looks like this:
Start Extension
Is there an API-Key in localStorage?
No => Display a input field and a save button which saves the key to localStorage; Yes => proceed with the Application:
App......
The only way I could think of it is putting it all together in a big View... but I guess since I am fairly new to this there are surely some better approaches.
You can create a model that maintains the state of the user's login status and a view that renders a different template depending on that status. The view can show the "input field" template if the user is not logged in and a different template if the user is. I would keep all access to localStorage in the Model because the View should not be concerned with persistence. The view should probably not be concerned with the API Key as well, and that's why I have my view binding to the model's loggedIn change ('change:loggedIn') instead of apiKey change...although I am showing the API key in one of my templates for demonstration purpose only. Here's my very simplified sample. Note that I didn't bother with validating the API Key, but you'll probably want to:
Templates:
<script id="logged_in" type="text/html">
You're logged in. Your API key is <%= escape('apiKey') %>. Let's proceed with the application...
</script>
<script id="not_logged_in" type="text/html">
<form class="api_key">
API Key: <input name="api_key" type="text" value="" />
<button type="sumit">Submit</button>
</form>
</script>
Backbone Model and View:
var LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
apiKey: null
},
initialize: function () {
this.bind('change:apiKey', this.onApiKeyChange, this);
this.set({'apiKey': localStorage.getItem('apiKey')});
},
onApiKeyChange: function (status, apiKey) {
this.set({'loggedIn': !!apiKey});
},
setApiKey: function(apiKey) {
localStorage.setItem('apiKey', apiKey)
this.set({'apiKey': apiKey});
}
});
var AppView = Backbone.View.extend({
_loggedInTemplate: _.template($('#logged_in').html()),
_notLoggedInTemplate: _.template($('#not_logged_in').html()),
initialize: function () {
this.model.bind('change:loggedIn', this.render, this);
},
events: {
'submit .api_key': 'onApiKeySubmit'
},
onApiKeySubmit: function(e){
e.preventDefault();
this.model.setApiKey(this.$('input[name=api_key]').val());
},
render: function () {
if (this.model.get('loggedIn')) {
$(this.el).empty().html(this._loggedInTemplate(this.model));
} else {
$(this.el).empty().html(this._notLoggedInTemplate(this.model));
}
return this;
}
});
var view = new AppView({model: new LoginStatus()});
$('body').append(view.render().el);

Categories

Resources