我第一次学习骨干js并试图让示例葡萄酒应用程序正常工作,它从数据库中提取并且列表视图显示用户列表但是当它调用WineDetails时它会抛出错误。< / p>
这是代码:
// Models
window.Wine = Backbone.Model.extend();
window.WineCollection = Backbone.Collection.extend({
model:Wine,
url:"../api/users"
});
// Views
window.WineListView = Backbone.View.extend({
tagName:'ul',
initialize:function () {
this.model.bind("reset", this.render, this);
},
render:function (eventName) {
_.each(this.model.models, function (wine) {
$(this.el).append(new WineListItemView({model:wine}).render().el);
}, this);
return this;
}
});
window.WineListItemView = Backbone.View.extend({
tagName:"li",
template:_.template($('#tpl-user-list-item').html()),
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
window.WineView = Backbone.View.extend({
template:_.template($('#tpl-user-details').html()),
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes:{
"":"list",
"users/:id":"wineDetails"
},
initialize:function () {
this.wineList = new WineCollection();
this.wineListView = new WineListView({model:this.wineList});
},
list:function () {
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
},
wineDetails:function (id) {
this.wine = this.wineList.get(id);
this.wineView = new WineView({model:this.wine});
$('#content').html(this.wineView.render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
和html
<div id="header"><span class="title">Backbone Cellar</span></div>
<div id="sidebar"></div>
<div id="content">
<h2>Welcome to Backbone Cellar</h2>
<p>
This is a sample application part of of three-part tutorial showing how to build a CRUD application with Backbone.js.
</p>
</div>
<!-- Templates -->
<script type="text/template" id="tpl-user-list-item">
<a href='#users/<%= user_id %>'><%= user_id %></a>
</script>
<script type="text/template" id="tpl-user-details">
<div class="form-left-col">
<label>Name:</label>
<input type="text" id="user_id" name="user_id" value="<%= user_id %>" required/>
</div>
</script>
</div>
和萤火虫中的错误
TypeError: this.model is undefined
$(this.el).html(this.template(this.model.toJSON()));
我尝试添加_.bindAll(this,“render”);在初始化函数中,但没有任何区别。
答案 0 :(得分:0)
在你的路由器中你只做wineList.fetch()。
您需要像下面的
一样处理成功回调wineList.fetch({success: function(){
$("#content").html(new WineListView({model: wineList, page: p}).el);
}});
我在github中使用backbone和requirejs实现了样本winecellar项目。 https://github.com/phillycoder/backbone-require-cellar