I am using a Router for my navigation and layout management (is that right!?) and seem to have a hit a problem:
backboneQuote.Routers.ApplicationRouter = Backbone.Router.extend({
routes: {
"" : "home",
"edit/:id": "quoteEdit"
},
initialize: function(){
this.headerView = new backboneQuote.Views.headerView();
$('.header').html(this.headerView.render().el);
if(!this.itemsView){
this.items = new backboneQuote.Collections.ApplicationCollection([
{id: 1, name: "item 1"},
{id: 2, name: "item 2"},
{id: 3, name: "item 3"}
]);
this.itemsView = new backboneQuote.Views.itemsView({collection: this.items});
}
this.content = $('.container');
},
home: function(){
this.content.html(this.itemsView.render());
},
quoteEdit: function(id){
this.editQuoteView = new backboneQuote.Views.editQuoteView({model: this.items.where({id: parseInt(id, 10)})});
$('#editQuote').html(this.editQuoteView.render().el);
this.content.html($('#editQuote').html());
}
});
My itemsView render stuff:
renderItem: function(model){
var itemView = new backboneQuote.Views.itemView({model: model});
itemView.render();
$(this.el).append(itemView.el);
return this;
},
render: function(){
this.collection.each(this.renderItem);
},
I click an element which navigates the app back to the “home” function (the click event is firing fine), but the content of “this.itemsView” never seem to get put back into “this.content” div. Can anyone spot anything wrong here?
As another massive help, if anyone could provide any overall BackboneJS wisdom on anything they see here then that would be a massive help.
Typically, in Backbone apps, we write the
rendermethod to set the content of the viewsel. It is the responsibility of the code that callsrenderto ensure that theelis shown at the right place.In the router,
you are not accessing the
.elproperty. First fix is to add that there.This assumes that your collection view has an
elproperty, which Backbone views by default tend to have.Considering this is such a common task, the convention is to return
thisat the end of each viewsrendermethod.