0
我已經通過代碼學校的Backbone.js的當然解剖工作,而是試圖挽救模式變回服務器時感到困惑。也許你可以幫忙。骨幹從JSON FETCH,然後編輯模型數據保存回JSON
這就是我所理解的需求發生:使用取
- 填充收集從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();
}
});
App.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