开发者

Does it make sense to initialize models from the DOM in backbone.js?

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?


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.


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:

<script type="text/js-template">
  <!-- Your template as realy do elements or using a js templating engine like _.template-->
</script>

Load up your page and have your app play locally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜