Just wondering why this works:
window.NewListView = Backbone.View.extend({
template: _.template('<a href="/list" class="button new-list">Create New List</a>'),
render: function(){
$(this.el).html(this.template());
return this;
}
});
window.List = new (Backbone.Router.extend({
routes: { "": "index" },
initialize: function(){
this.newListView = new NewListView();
},
start: function(){
Backbone.history.start();
},
index: function(){
$('.lists').append(this.newListView.render().el);
}
}));
$(function(){ List.start(); })
And this doesn’t:
window.NewListView = Backbone.View.extend({
template: _.template('<a href="/list" class="button new-list">Create New List</a>'),
render: function(){
$(this.el).html(this.template());
return this;
}
});
window.List = new (Backbone.Router.extend({
routes: { "": "index" },
initialize: function(){
this.newListView = new NewListView();
$('.lists').append(this.newListView.render().el);
},
start: function(){
Backbone.history.start();
},
index: function(){
}
}));
$(function(){ List.start(); })
The difference is just moving
$('.lists').append(this.newListView.render().el);
between initialize() and index() of the router.
Its because of the way, and when, you’re creating an instance of your router.
When you do:
You’re creating an instance of the router before the DOM is loaded. Therefore, in your
initializefunction, your jQuery selector is not returning any nodes.If you open up a console, you can see the order of operations logged to it on this jsFiddle:
http://jsfiddle.net/edwardmsmith/x64hw/
Results in:
But, if you create your router instance after the DOM loads:
The order is as you would expect, and it works:
as shown in this jsFiddle:
http://jsfiddle.net/edwardmsmith/eDWfh/