我已经阅读了关于同一主题的其他帖子,也许我在自己的代码中遗漏了一些东西,但在我看来,事情应该可以正常工作。我从未使用过 localStorage 和骨干网,似乎在这里遗漏了一些东西。任何想法都非常感谢!
我的实例:
var Address = {
run: function() {
this.router = new AddressRouter();
this.contactscollection = new AddressCollection();
this.addContact = new AddressAddView();
this.listView = new AddressListView();
Backbone.history.start();
}
};
我的收藏:
var AddressCollection = Backbone.Collection.extend({
model: AddressModel,
localstorage: new Store('backbone-addressbook')
});
我的模型:
var AddressModel = Backbone.Model.extend({
defaults: {
id: '',
name: '',
email: ''
}
});
和我的观点:
var AddressAddView = Backbone.View.extend({
el: '#content',
template: _.template($('#addContactTemplate').html()),
events: { 'submit form#addContactForm': 'createContact'},
createContact: function(){
Address.contactscollection.create(this.newAttributes());
this.save();
this.input.val('');
},
newAttributes: function() {
return {
id: $('#id').val(),
name: $('#name').val(),
email: $('#email').val()
}
},
initialize: function() {
_.bindAll(this, 'addContactPage','render');
},
addContactPage: function(id) {
var contact = {},
model = Address.contactscollection.get(id);
if (id !== undefined && model !== undefined) {
contact = model.toJSON();
}
this.$el.html(this.template({contact: contact}));
}
});