我无法理解“saveWine”方法中的“app.wineList.create(this.model)”是什么。它会如何工作?我是backbone.js的新手,请帮助我理解这一点。我知道this.model.save()。
其实我在这里删除了一些代码。我刚发布了问题所在的代码。
感谢。
// Models
window.Wine = Backbone.Model.extend({
urlRoot:"../api/wines",
defaults:{
"id":null,
"name":"",
"grapes":"",
"country":"USA",
"region":"California",
"year":"",
"description":"",
"picture":""
}
});
window.WineCollection = Backbone.Collection.extend({
model:Wine,
url:"../api/wines"
});
// Views
window.WineView = Backbone.View.extend({
template:_.template($('#tpl-wine-details').html()),
initialize:function () {
this.model.bind("change", this.render, this); // (event, function, context)
},
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events:{
"click .save":"saveWine"
},
saveWine:function () {
this.model.set({
name:$('#name').val(),
grapes:$('#grapes').val(),
country:$('#country').val(),
region:$('#region').val(),
year:$('#year').val(),
description:$('#description').val()
});
if (this.model.isNew()) {
app.wineList.create(this.model);
} else {
this.model.save();
}
return false;
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes:{
"":"list",
"wines/:id":"wineDetails"
},
initialize:function () {
$('#header').html(new HeaderView().render().el);
},
list:function () {
this.wineList = new WineCollection();
this.wineListView = new WineListView({model:this.wineList});
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
},
wineDetails:function (id) {
this.wine = this.wineList.get(id);
if (app.wineView) app.wineView.close();
this.wineView = new WineView({model:this.wine});
$('#content').html(this.wineView.render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
答案 0 :(得分:1)
在集合中创建模型的新实例的便利性。 相当于使用属性哈希实例化模型,保存 将模型添加到服务器,然后将模型添加到集合中 成功创建。
因此,它会为您的winelist集合添加一个模型,并将其保存到服务器。