Home >Web Front-end >JS Tutorial >Examples to explain the View view in the Backbone.js framework of JavaScript_Basic knowledge

Examples to explain the View view in the Backbone.js framework of JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:02:101634browse

The View in Backbone is used to reflect the appearance of the Model in your app. They listen for events and react accordingly.
In the following tutorial, I won't tell you how to bind Models and Collections to Views. Instead, I will focus on how Views use javascript template libraries, especially Underscore.js's _.template.
Here we use jQuery to manipulate DOM elements. Of course, you can also use other libraries, such as MooTools or Sizzle, but Backbone's official documentation recommends that we use jQuery.
Next, let’s 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();

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

el attribute
The el attribute refers to the DOM object that has been created in the browser. Each View has an el attribute. If it is not defined, Backbone will create an empty div element as 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 time, the el attribute of View refers to the div element with the id of search_container. We have now bound this div element, so any events we want to trigger must be in this div element.

Load template
Backbone is strongly dependent on Underscore.js, so we can use small templates 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 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(){
      // 通过 Underscore 编译生成模板
      var template = _.template( $("#search_template").html(), {} );
      //讲生成的模板加载到 el 属性中
      this.$el.html( template );
    }
  });

  var search_view = new SearchView({ el: $("#search_container") });
</script>

Add listening event
We use the events attribute of View to add listening events. Remember that listening events can only be added to 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 ){
      // 当 button 被点击时触发 alert 
      alert( "Search for " + $("#search_input").val() );
    }
  });

  var search_view = new SearchView({ el: $("#search_container") });
</script>

Pass parameters to the template
Template can use parameters passed from View in the form of 332000003288cabbdff89f9a8e5a919b.

<script type="text/template" id="search_template">
  <!-- 通过 <%= %> 形式使用传来的参数 -->
  <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(){
      //定义需要传递的参数
      var variables = { search_label: "My Search" };
      // 通过 Underscore 生成模板,同时传递参数
      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>

Handling DOM events
A very important feature of views is to help us automatically bind interface events. Recall how we bound events to interface labels before? It might look 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 have developed some complex applications, you may have tried to better organize these codes in some way to make them The structure seems clearer and easier to maintain.
Backbone's view object provides us with an automatic binding mechanism for events 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 put four buttons in a label with the id of view, and associated this label with the view class MyView.
When defining the view class, we declared an events attribute, which represents the list of user events in the view, described as follows:
事件名称 选择器 : 事件处理函数
The event name can be any event supported by the DOM object, the selector can be any selector string supported by jQuery or Zepto (including label selector, class selector, id selector, etc.), and the event handling function should have been defined in The method name of the view class itself.
The view object automatically parses the description in the events list, that is, uses jQuery or Zepto to obtain the DOM object described by the selector, and binds the event handler function to the event name. These operations will be completed automatically when the view class is instantiated. We can care more about the structure of the view class itself instead of deliberately thinking about how to bind events.

你可能在擔心另一個問題:如果視圖的DOM結構是動態產生的,Backbone是否提供了相應的方法用於動態綁定和解除事件?
其實你並不需要關心這個問題,因為events中的事件是透過delegate()方法綁定到視圖物件的el元素上,而並非是選擇器所描述的元素。因此視圖內的結構無論如何變化,events中的事件都是有效的。
(如果你對jQu​​ery比較熟悉,可能了解它所提供的delegate()方法。該方法實際上將事件綁定在父層元素,然後在事件冒泡過程中,透過檢查目標子元素來觸發事件。)
視圖物件透過delegate()方法綁定事件,表示我們不需要關心視圖結構變化對事件產生的影響,同時也說明events中選擇器所對應的元素必須處於視圖的el元素之內,否則綁定的事件是無法生效的。

儘管如此,有些情況下可能我們仍然需要手動綁定和解除事件,視圖對象提供了delegateEvents()和undelegateEvents()方法用於動態綁定和解除events事件列表,你可以通過查看API文檔來了解它們。
渲染視圖與資料
視圖主要用於介面事件的綁定和資料渲染,然而視圖物件僅僅提供了一個和渲染相關的方法render(),並且它是一個沒有任何邏輯、也沒有任何地方引用到的空方法,我們需要重載它來實現自己的渲染邏輯。
視圖中可能包含許多介面邏輯​​,這裡建議所有的視圖子類別都重載render()方法,並將它作為最終渲染的入口方法。在團隊開發中,嚴格遵守規範編碼可以幫助別人更好地理解和維護你的程式碼。  

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn