我一直在学习 Code School 的 Anatomy of Backbone.js 课程,但在尝试将模型更改保存回服务器时感到困惑。也许你可以帮忙。
这就是我理解需要发生的事情:
- 使用 fetch() 从 JSON 数据源填充集合;
- 将集合附加到 DOM
- 编辑模型(取消选中复选框,将“收藏夹”设置为 false)
- 保存模型。
我的假设是,如果我取消选择一条记录作为“收藏夹”然后点击刷新,则更改将是持久的,并且在 JSON 文件中也很明显。但是,情况并非如此,原始集合已加载且 JSON 未更改。
我认为我的困惑在于使用 fetch 方法并在模型和集合中声明 URL。
我怎样才能使这种模型更改保持不变?
模型:
var Contact = Backbone.Model.extend({
url: '/contacts',
defaults:{
favourite: false
},
toggleFavourite: function(){
if(this.get('favourite') === false)
{
this.set({ 'favourite': true });
} else {
this.set({ 'favourite': false })
}
this.save();
}
});
收藏
var Contacts = Backbone.Collection.extend({
model: Contact,
url: '/contacts'
});
意见
var ContactView = Backbone.View.extend({
className: 'record',
template: _.template('<span><%= name %></span>' +
'<span class="phone-number"><%= phone %></span>' +
'<input type="checkbox" <% if(favourite === true) print("checked") %>/>'),
events: {
'change input': 'toggleFavourite',
'click .phone-number': 'dial'
},
initialize: function(){
this.model.on('change', this.render, this);
},
toggleFavourite: function(e){
this.model.toggleFavourite();
},
dial: function(e){
alert('Dialing now...');
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var ContactsView = Backbone.View.extend({
initialize: function(){
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(contact){
var contactView = new ContactView({ model: contact });
this.$el.append(contactView.render().el);
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
render: function(){
this.addAll();
}
});
应用程序.js
var contacts = new Contacts(); //creates list
contactsView = new ContactsView({ collection: contacts}); //creates list view
contacts.fetch({url: 'contacts/data.json'}); //populates list
$('#mainPanel').append(contactsView.el); //appends list to DOM