Bra*_*cil 3 local-storage backbone.js
演示小提琴(有问题)http://jsfiddle.net/mjmitche/UJ4HN/19/
我有一个像这样定义的集合
var Friends = Backbone.Collection.extend({
model: Friend,
localStorage: new Backbone.LocalStorage("friends-list")
});
Run Code Online (Sandbox Code Playgroud)
据我所知,这就是我需要做的就是让本地存储工作(除了将它包含在backbone.js之下)
有一件事我不确定,名称"friends-list"是否必须与DOM元素对应?我正在尝试保存"friends-list",所以我称之为在本地存储中,但localstorage似乎不需要传递类或id.
这是一个小提琴,你可以看到我正在尝试做什么http://jsfiddle.net/mjmitche/UJ4HN/19/
在我的本地网站上,我正在添加几个朋友,刷新页面,但朋友们没有重新出现.
更新
我在我的本地网站上的代码中也完成了以下操作
console.log(Backbone.LocalStorage);
Run Code Online (Sandbox Code Playgroud)
它并没有抛出错误.
我尝试调试
我在window.AppView中尝试了这段代码(取自另一个SO答案)但控制台中没有任何内容.
this.collection.fetch({}, {
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
})
Run Code Online (Sandbox Code Playgroud)
从精细手册:
相当简单的Backbone的localStorage适配器.它是Backbone.Sync()的替代品,用于处理对localStorage数据库的保存.
这个LocalStorage插件只是Backbone.Sync的替代品,所以你仍然需要save你的模型和fetch你的收藏.
由于您没有保存任何内容,因此您永远不会将任何内容放入LocalStorage数据库.您需要保存模型:
showPrompt: function() {
var friend_name = prompt("Who is your friend?");
var friend_model = new Friend({
name: friend_name
});
//Add a new friend model to our friend collection
this.collection.add(friend_model);
friend_model.save(); // <------------- This is sort of important.
},
Run Code Online (Sandbox Code Playgroud)
您也可能想要使用success和error回调friend_model.save().
由于您没有fetch任何东西,因此不要使用LocalStorage数据库中的任何内容初始化您的集合.你需要调用fetch你的集合,你可能想绑定render到它的"reset"事件:
initialize: function() {
_.bindAll(this, 'render', 'showPrompt');
this.collection = new Friends();
this.collection.bind('add', this.render);
this.collection.bind('reset', this.render);
this.collection.fetch();
},
Run Code Online (Sandbox Code Playgroud)
您还需要更新您的render能够呈现整个集合:
render: function() {
var $list = this.$('#friends-list');
$list.empty();
this.collection.each(function(m) {
var newFriend = new FriendView({ model: m });
$list.append(newFriend.render().el);
});
$list.sortable();
return this;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过将"添加一个模型的视图"逻辑移动到单独的方法并将该方法绑定到集合的"add"事件来使这更好.
还有一个简化版本的小提琴:http://jsfiddle.net/ambiguous/haE9K/