演示 fiddle (有问题)http://jsfiddle.net/mjmitche/UJ4HN/19/
我有一个这样定义的集合
var Friends = Backbone.Collection.extend({
model: Friend,
localStorage: new Backbone.LocalStorage("friends-list")
});
据我所知,这就是让本地存储正常工作所需要做的一切(除了将其包含在 backbone.js 之下)
有一件事我不确定,名称“friends-list”是否必须对应于 DOM 元素?我试图保存“ friend 列表”,所以我在本地存储中称它为本地存储,但是,本地存储似乎不需要传递类或 ID。
这是一个 fiddle ,您可以在其中看到我正在尝试做的事情 http://jsfiddle.net/mjmitche/UJ4HN/19/
在我的本地站点上,我添加了几个 friend ,刷新了页面,但这些 friend 没有重新出现。
更新
我还在本地站点的代码中完成了以下操作
console.log(Backbone.LocalStorage);
并且它没有抛出错误。
我的调试尝试
我在 window.AppView 中尝试了这段代码(取自另一个 SO 答案),但控制台中没有显示任何内容。
this.collection.fetch({}, {
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
})
最佳答案
来自fine manual :
Quite simply a localStorage adapter for Backbone. It's a drop-in replacement for Backbone.Sync() to handle saving to a localStorage database.
此 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.
},
您可能还想在 friend_model.save()
上使用 success
和 error
回调。
因为您没有获取
任何东西,所以您不需要使用 LocalStorage 数据库中的任何内容来初始化您的集合。您需要对您的集合调用 fetch
并且您可能希望将 render
绑定(bind)到它的 "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();
},
您还需要更新您的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;
}
您可以通过将“添加一个模型的 View ”逻辑移动到一个单独的方法并将该方法绑定(bind)到集合的 “add”
事件来改善这一点。
以及您的 fiddle 的精简和修复版本:http://jsfiddle.net/ambiguous/haE9K/
关于Backbone.js:只需一行设置本地存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12537316/