只是想知道为什么会这样:
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(); })
这不是:
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(); })
区别在于移动
$('.lists').append(this.newListView.render().el);
在路由器的initialize()和index()之间。
答案 0 :(得分:5)
这是因为你正在创建路由器的实例,以及何时,
当你这样做时:
window.List = new (Backbone.Router.extend({...
在加载DOM之前,您正在创建路由器的实例。因此,在initialize
函数中,您的jQuery选择器不会返回任何节点。
如果你打开一个控制台,你可以在这个jsFiddle上看到记录到它的操作顺序:
http://jsfiddle.net/edwardmsmith/x64hw/
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();
console.log("List Initialize");
$('.lists').append(this.newListView.render().el);
},
start: function(){
Backbone.history.start();
},
index: function(){
}
}));
$(function(){
console.log("Before List Start");
List.start();
console.log("After List Start");
})
结果:
List Initialize
Before List Start
After List Start
但是,如果在DOM加载后创建路由器实例:
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 = Backbone.Router.extend({
routes: { "": "index" },
initialize: function(){
this.newListView = new NewListView();
console.log("List Initialize");
$('.lists').append(this.newListView.render().el);
},
start: function(){
Backbone.history.start();
},
index: function(){
}
});
$(function(){
console.log("Before List Start");
list = new List();
list.start();
console.log("After List Start");
})
订单如您所料,并且有效:
Before List Start
List Initialize
After List Start
如jsFiddle所示: