The View in backbone is used to reflect the Model in your app. They listen to events and respond accordingly.
The next tutorial I won't tell you how to bind Model and Collection to view, but rather to discuss how View uses JavaScript template libraries, especially underscore.js ' s _.template.
Here we use jquery to manipulate DOM elements, and of course you can use other libraries, such as MooTools or Sizzle, but Backbone's official document recommends that we use jquery.
Next, we take the search box as an example to create a new View:
Searchview = Backbone.View.extend ({
initialize:function () {
alert ("Welcome to backbone!");
}
);
var search_view = new Searchview ();
Either Model,view or Collection, the Initialize () method is automatically triggered when instantiated.
El Property
the El attribute refers to a DOM object that has been created in the browser, and each View has an El attribute, and if it is not defined, backbone will create an empty div element for the El attribute.
Let's create an El attribute for View and set it to #search_containe.
<div id= "Search_container" ></div>
<script type= "Text/javascript" >
Searchview = Backbone.View.extend ({
initialize:function () {
alert ("Welcome to backbone!");
}
);
var search_view = new Searchview ({el: $ ("#search_container")});
</script>
At this point, View's El attribute refers to a DIV element with ID search_container. We now bind this div element, so any event we want to trigger must be in this div element.
Load Template
backbone is strongly dependent on underscore.js, so we can use a small template in Underscore.js.
Now, let's add a render () method and call it in Initialize () so that the render () method is automatically triggered when the View is initialized.
This render () method will load the template into the View's El attribute through JQuery.
<script type= "Text/template" id= "search_template" >
<label>Search</label>
<input type = "text" id= "Search_input"/>
<input type= "button" id= "Search_button" value= "search"/>
</script >
<div id= "Search_container" ></div>
<script type= "Text/javascript" >
searchview Backbone.View.extend ({
initialize:function () {
this.render ();
},
render:function () {
//through Underscore compile generate template
var template = _.template ($ ("#search_template"). HTML (), {});
The generated template is loaded into the El attribute this
. $el. html (template);
}
});
var search_view = new Searchview ({el: $ ("#search_container")});
</script>
Add a Listener Event
we use the View's Events property to add a listener event, remembering that the listener event can only be added to the child elements of the El attribute. Now, let's add a listener event to the child element button.
<script type= "Text/template" id= "search_template" >
<label>Search</label>
<input type = "text" id= "Search_input"/>
<input type= "button" id= "Search_button" value= "search"/>
</script >
<div id= "Search_container" ></div>
<script type= "Text/javascript" >
searchview Backbone.View.extend ({
initialize:function () {
this.render ();
},
render:function () {
var Template = _.template ($ ("#search_template"). HTML (), {});
this. $el. html (template);
},
events: {
"click Input[type=button]": "Dosearch"
},
Dosearch : function (Event) {
//Trigger Alert Alert when button is clicked
("Search for" + $ ("#search_input"). Val ());
;
var search_view = new Searchview ({el: $ ("#search_container")});
</script>
Passing parameters to a template
templates can be used in the form of <%=%> to use parameters from View.
<script type= "Text/template" id= "Search_template" > <!--using the <%=%> form the parameters that came from--> <label><%= Search_label%></label> <input type= "text" id= "Search_input"/> "<input type=" button "id=" Search_but Ton "value=" Search/> </script> <div id= "Search_container" ></div> <script type= "text/"
JavaScript "> Searchview = Backbone.View.extend ({initialize:function () {this.render ();
}, Render:function () {//define the parameters to be passed var variables = {search_label: "My Search"};
Generate templates through underscore, while passing parameters var template = _.template ($ ("#search_template"). HTML (), variables);
Load the compiled HTML into the backbone "El" this. $el. html (template); Events: {"Click Input[type=button]": "Dosearch"}, Dosearch:function (event) {alert ("Searc
H for "+ $ (" #search_input "). Val ());
}
}); var search_view = new Searchview ({el: $ ("#search_container") });
</script>
Handling DOM Events
an important feature of a view is that it helps us automatically bind interface events. Recall how we used to bind events for interface tags? It might be like this:
<p>
<input type= "button" value= "Create" id= "create"/> <input type=
"button" value= "Read" id= " Read "/>
<input type=" button value= "Update" id= "Update"/> <input "
button" type= "Delete" id = "Delete"/>
</p>
<script type= "text/javascript" >
function Createdata () {
//TODO
}
function ReadData () {/
/TODO
}
function UpdateData () {
//TODO
}
function DeleteData () {
//Todo
}
$ (' #create '). On (' click ', Createdata);
$ (' #read '). On (' click ', ReadData);
$ (' #update '). On (' click ', UpdateData);
$ (' #delete '). On (' click ', DeleteData);
</script>
This is an example of a typical jquery-bound DOM event, and if you are developing or have developed some complex applications, you may have tried to organize the code in some way to make it look better and more maintainable.
The backbone View object provides an automatic binding mechanism for events to better maintain the relationship between DOM and events to see the following examples:
<p id= "View" >
<input type= "button" value= "Create" id= "create"/> <input type=
"button" value= " Read "id=" read "/>
<input type=" button "value=" Update "id=" Update "/> <input type=
" button "value=" Delete "id=" delete "/>
</p>
<script type=" Text/javascript ">
var myview = Backbone.View.extend ({
el: ' #view ',
events: {
' click #create ': ' Createdata ',
' click #read ': ' ReadData ',
' click #update ': ' UpdateData ',
' click #delete ': ' DeleteData '
},
createdata:function () {/
/Todo
},
readdata:function () {
//Todo
},
updatedata:function () {
//todo< c23/>},
deletedata:function () {
//Todo
}
});
var view = new MyView ();
</script>
In this example, we put 4 buttons in a tab with an ID of view and associate the tag with the view class MyView.
When defining the view class, we declare a events property that represents the list of user events in the view, as follows:
Event name selector: event handler function
The event name can be any event supported by the DOM object, and the selector can be any selector string (including tag Selector, class selector, ID selector, etc.) that is supported by jquery or Zepto, and the event handler function should be the name of the method already defined in the view class itself.
The View object automatically parses the description in the events list by using jquery or Zepto to get the DOM object described by the selector and binding the event handler function to the event name. These actions are automatically completed when the view class is instantiated, and we can be more concerned with the structure of the view class itself than by deliberately considering how to bind the event.
You may be worrying about another question: if the DOM structure of the view is dynamically generated, does backbone provide the appropriate method for dynamically binding and unblocking events?
You don't really need to care about this, because events in event are bound to the El element of the View object by the delegate () method, not the element that the selector describes. So the structure in the view changes in any case, and events in the event are valid.
(If you are familiar with jquery, you may understand the delegate () method it provides.) The method actually binds the event to the parent layer element, and then triggers the event during event bubbling by examining the target child element. )
The View object binds events through the delegate () method, meaning that we do not need to care about the impact of changes in the view structure on events, but also that the elements of the selector in events must be within the El element of the view, otherwise the bound event cannot take effect.
Nevertheless, in some cases we may still need to bind and disassociate the events manually, and the View object provides the Delegateevents () and Undelegateevents () methods for dynamically binding and unblocking the events list. You can learn about them by looking at the API documentation. The
rendering view and data
view is primarily used for binding and data rendering of interface events, whereas a View object merely provides a rendering-related method render (), and it is an empty method without any logic or reference anywhere. We need to overload it to implement our own rendering logic. The
view may contain many interface logic, and it is recommended that all view subclasses overload the render () method as the final rendering entry method. In team development, strict coding can help others understand and maintain your code better.