First, dynamic view
1. There are basically 2 ways to render views now
(1) The server generates good HTML;
(2) Client render template, the server side provides the JSON data interface.
2, the client renders the view also has 2 kinds of ways:
(1) Use document.createelement to create DOM elements and append them to the page;
(2) Pre-defined HTML static view, display and hide HTML fragments when necessary;
Second, the template
1, now, there are many templates can choose, such as mustache, underscore simple template, handlebars, ejs and so on. The template engine is a simple and practical way to display a small template engine on its own. Template syntax is also simple, for example:
{{if}}
${url}
{{/if}}
Or
<%if%>
<%=name%>
<%endif%>
If you put the back-end business logic code and view rendering to the front end, it is recommended to use the template engine, although it wastes HTML fragments, such as
<script type= "TEXT/MY-TPL" >
Name is:<%=name%>
</script>
This HTML snippet is not rendered, and the UI is displayed only when the template engine gets the data and render the template. The advantage of this is that the separation of views and logic can guarantee the rationality of MVC and improve the maintainability of the code.
2. Where to put the template
(1) exist in JS code;
(2) defined in the script tag, as shown in the example above;
(3) pull through Ajax;
(4) HTML in-line storage
The (2) scheme has some advantages, which ensures that the MVC separation does not have to be pulled remotely like (3), and that the HTML in-line storage can not only render the UI directly, but also ensure that the source code is clear; (2) The program is more flexible and easier to maintain and control.
Third, the binding between the view and the model
1two-way data binding with ANGULARJS must be cool, it's just sour. When the JS object changes, it can cause the view to refresh without having to manually2 Refresh rendering of the view. The practice here is to immediately notify the view of the update of the model to render. 3 For example:4 varUser =function(){5 This. Name =name;6 };7 //Defining Bindings8User.bind =function(event, callback) {9 varcalls = This. _callbacks | | ( This. _callbacks = {});Ten( This. _callbacks[event] | | ( This. _callbacks[event] =[]). push (callback); One }; A //Event Triggering -User.trigger =function(event) { - if(! This. _callbacks)return This; the if(! This. _callbacks[evnet])return This; - varList = This. _callbacks[evnet]; -$.each (list,function(){ - This(); + }); - }; + AUser.create =function(name) { at This. Records.push (New This(name)); - This. Trigger (' Change '); - }; - - //Bind Change Event -$(function($){ inUser.bind (' Change ',function(){ - varTPL = ' <li>test</li> '; to$ (' #list '). empty (); +$ ('#list). Append (TPL); - }); the});
Building the underlying JavaScript mvc--views and templates (ii)