从 localStorage 转换 Backbone 的待办事项列表示例
我一直在查看 待办事项列表示例 (源) Backbone.js。该代码使用本地存储,我想尝试对其进行转换,以便它通过 RESTful Web 服务进行操作。
假设 web 服务已存在于路由 todos/
处。我想我需要将 url
片段添加到 Backbone.Model.extend
中,并删除 localStorage: new Store("todos")
行当我们执行 Backbone.collection.extend 时。
window.Todo = Backbone.Model.extend({
url : function() {
return 'todos/'+this.id;
}
// Default attributes for a todo item.
defaults: function() {
return {
done: false,
order: Todos.nextOrder()
};
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
}
});
执行此操作的正确方法是什么?
I have been looking at the Todo list example (source) for Backbone.js. The code uses local storage, and I wanted to try and convert it so that it operated via a RESTful webservice.
Suppose the webservice already exists at the route todos/
. I figured I need to add in a url
piece into Backbone.Model.extend
and remove the localStorage: new Store("todos")
line when we perform Backbone.collection.extend
.
window.Todo = Backbone.Model.extend({
url : function() {
return 'todos/'+this.id;
}
// Default attributes for a todo item.
defaults: function() {
return {
done: false,
order: Todos.nextOrder()
};
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
}
});
What is the proper way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要与集合创建的 URL 不同的 url,而不是在模型中声明 url,则应在 Collection 中设置 Url。
您需要
从index.html中删除,因为它链接在backbone.js之后,并有效地覆盖Backbone的同步方法以存储在localStorage中。
Url should be set in Collection, if you have need for diferent urls than those created by collection than declare url in model.
You need to remove
from index.html since it is linked after backbone.js and effectively overrides Backbone's sync method to store in localStorage.
我将保留 Todos 示例中的模型。在集合类中添加此属性:
在集合上调用
fetch()
应检索 Todo 对象的列表。如果您使用 Rails,则需要设置
ActiveRecord::Base.include_root_in_json = false
否则 Backbone.js 将无法从返回的 json 中提取 Todo 对象。I would leave the model as it is in the Todos example. In the collection class add this property:
Calling
fetch()
on the collection should retrieve a list of Todo objects.If you are using Rails you need to set
ActiveRecord::Base.include_root_in_json = false
otherwise Backbone.js will not be able to pull out the Todo objects from the returned json.