Tags: style http color io os using java AR data
This period of time in the process of learning require.js and backbone.js, found that some of the project's HTML code is written in the view of the JS code inside, when the rendering needs to loop on the collection, and then the HTML code splicing up, which seems to be not a very good thing, because the JS generation Code and HTML code together will increase the difficulty of maintenance, and this process takes into account the performance factors, you need to put the HTML code in an array, and finally splicing, the code is more cumbersome to write. After I saw their code, I was thinking about whether there was something like a php template engine that could pass collection in and render it.
I consulted Backbone.js's Handbook http://backbonejs.org/#View-template, which contained a text:
It is recommended that we use JS Template Library, and just backbone.js strongly dependent on underscore.js so underscore.js has been introduced, it provides a _.template method, this method supports the use of embedded JS Code HTML template Code, In the JS code does not appear HTML code is a very nice thing! This is in line with our MVC idea, the front-end HTML code is also easy to maintain, otherwise it really becomes spaghetti code!
A description of Underscore.js's template is in the http://underscorejs.org/#template, and here's how you can use it.
The above text tells us in this template code inside the JS embedded code tag How to use, next I give an example:
We'll build a template, located at: template/album/index.html?
The code snippet below defines a backbone View,sync property that asks the server to get all the album data, and then stores the data in the collection of Albumlist. The Render method is then executed, in render inside This.template = _.template (albumtpl, albums); This code is used to complete the work of mixing data and templates, Albumtpl from Template/album /index.html, you must also have all the model in the collection in the form of an array to be assigned to albums, unless you are in the template and collection parsing operation, otherwise you can not only pass in a collection, because Underscore.js's The template is an object structure that does not recognize Backbone.js's collection.?
Through the above operation, you can implement the JS code and HTML code separation.
Use Underscore.js's template to separate Backbone.js's JS code from the HTML code