在backbone.js 中从 DOM 初始化模型有意义吗?
backbone.js 依赖于 Restful 应用程序来初始化模型,但是渐进增强呢?数据已经在 dom(或其中的一些)中,所以即使 html 元素存在,我的模型仍然应该调用 Restful 接口吗?是否有另一种库设计可能更适合这种情况?
backbone.js relies on restful applications to initialize models, but what about progressive enhancement? The data is already in the dom (or some of it), so should my models still make calls the the restful interface even though the html elements exist? Is there another library design that might be better suited for this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Backbone 可以很好地处理这个问题。我处理这种情况的方法是拥有一个工厂模型,它可以接收 DOM 节点并解析它以提取数据(id、字段等)。
如果您向 View 构造函数提供 'el' 选项,backbone 将不会获取也不渲染模型,因此您可以保持节点不变。
数据更改后,控制器将同步到服务器。不过,无论是否显示,您都必须小心地包含应用程序运行所需的任何数据。
Backbone can handle that pretty well. The way I handle this case is to have a factory model that can receive a DOM node and parse it in order to extract data (id, fields and so on).
If you supply a 'el' option to a View constructor, backbone won't fetch nor render the model, so you can keep your node as is.
Upon data change, the controller will then sync to the server. You must be careful though to include whatever data your application needs to function whether it's displayed or not.
您不应该使用 DOM 元素通过后端数据初始化模型。你有一个非常好的基础设施,有骨干,不会这样做。例如,当您依赖 DOM 时,只要 DOM 结构因设计而发生变化,您就需要更改 JavaScript。
也不依赖主干视图来创建模型。它必须反过来,模型决定页面上的视图。
只需添加一个脚本元素并直接在其中创建 JS 对象即可。您可以初始化集合、单个模型等。
您可以使用模板或 DOM UI 构建块执行相同的操作:
加载页面并让您的应用程序在本地播放。
You should not use DOM element to initialize your model with backend data. You have a really nice infrastructure with backbone to not do this. When you rely on the DOM you need to change your javascript whenever the DOM structure change due to design for exemple.
Also do not rely on backbone view to create the model. It must go the other way around, the model dictate the views on the page.
Just add a script element and create your JS objects directly in there. You can initialize collections, single models, etc.
You can do the same with templates or DOM UI building blocks:
Load up your page and have your app play locally.