The example explains the View in the Backbone. js framework of JavaScript, including javascriptbackbone.

Source: Internet
Author: User

The example explains the View in the Backbone. js framework of JavaScript, including javascriptbackbone.

The View in Backbone is used to reflect the Model in your app. They listen to events and respond accordingly.
In the next tutorial, I will not tell you how to bind the Model and Collection to the View, but mainly discuss how the View uses the javascript template library, especially Underscore. js's _. template.
Here we use jQuery to operate DOM elements. Of course you can also use other libraries, such as MooTools or Sizzle. However, jQuery is recommended in official documents of Backbone.
Next, we will use 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();

Whether it is Model, View or Collection, the initialize () method is automatically triggered when it is instantiated.

El attributes
The el attribute refers to a DOM object that has been created in the browser. Each View has an el attribute. If it is not defined, backbone creates an empty div element as the el attribute.
Next let's create an el attribute for the 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>

In this case, the el attribute of View refers to the div element whose id is 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 loads the template to the el attribute of the View 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 () {// generate the var template = _. template ($ ("# search_template" ).html (), {}); // load the generated template to the el attribute this.$el.html (template );}}); var search_view = new SearchView ({el: $ ("# search_container")}); </script>

Add listener events
We use the events attribute of View to add listening events. Remember that listening events can only be added to sub-elements of the el attribute. Now, we will 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) {// triggers alert ("Search for" + $ ("# search_input") when a button is clicked "). val () ;}}); var search_view = new SearchView ({el :$ ("# search_container")}); </script>

Pass parameters to the template
The template can use parameters in the form of <% = %> from the View.

<Script type = "text/template" id = "search_template"> <! -- Use transmitted parameters in the form of <% =%> <label> <% = search_label %> </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 () {// define the parameter var variables to be passed = {search_label: "My Search"}; // generate a template through Underscore, at the same time, pass the parameter 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 ("Search for" + $ ("# search_input "). val () ;}}); var search_view = new SearchView ({el :$ ("# search_container")}); </script>

Process DOM events
An important feature of a view is to help us automatically bind interface events. Recall how we previously bound events to the interface tag? It may 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 type="button" value="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 a typical example of binding DOM events through jQuery. If you are developing or developing complex applications, you may have tried to better organize these codes in some way, to make them look clearer and easier to maintain.
The view object of Backbone provides an automatic event binding mechanism for us to better maintain the relationship between DOM and events. Let's take a look at the following example:

<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     },     deleteData : function() {       // todo     }   });   var view = new MyView(); </script> 

In this example, we place the four buttons in a tag with the view id, and associate the tag with the view class MyView.
When defining a View class, we declare an events attribute, which indicates the list of user events in the view. The description is as follows:
Event name selector: event processing function
The event name can be any event supported by the DOM object, and the selector can be any selector string supported by jQuery or Zepto (including the tag selector, class selector, and id selector ), the event handler function should be the method name defined in the View class itself.
The view object automatically parses the description in the events list, that is, the DOM object that uses jQuery or Zepto to obtain the selector description, and binds the event processing function to the event name. These operations are automatically completed when the View class is instantiated. we can focus more on the structure of the View class, rather than deliberately considering how to bind events.

You may be worried about another problem: if the view's DOM structure is dynamically generated, does Backbone provide the corresponding method for dynamic binding and event relief?
In fact, you do not need to care about this issue, because events in events are bound to the el element of the view object through the delegate () method, rather than the element described by the selector. Therefore, no matter how the structure in the view changes, events in the events are valid.
(If you are familiar with jQuery, you may be familiar with the delegate () method provided by jQuery. This method actually binds the event to the parent layer element, and then checks the target sub-element to trigger the event during event bubbling .)
The view object binds events using the delegate () method, meaning that we do not need to care about the impact of view structure changes on events, it also indicates that the element corresponding to the selector in events must be within the el Element of the view, otherwise the Bound event cannot take effect.

Even so, in some cases, we may still need to manually bind and unbind events. The view object provides the delegateEvents () and undelegateEvents () methods for dynamically binding and removing the events event list, you can view the API documentation to learn about them.
Rendering views and data
The view is mainly used for binding interface events and Data Rendering. However, the view object only provides a rendering-related method render (), and it is an empty method without any logic or any reference. We need to reload it to implement our own rendering logic.
A view may contain many interface logics. It is recommended that all view subclasses reload the render () method and use it as the final rendering entry method. In team development, strict coding can help others better understand and maintain your code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.