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

May 16, 2016 pm 03:02 PM
backbone javascript view view

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();
Copy after login

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>

Copy after login

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>

Copy after login

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>

Copy after login

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

<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>

Copy after login

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> 

Copy after login

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> 
Copy after login

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:
事件名称 选择器 : 事件处理函数
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Understand the differences and comparisons between SpringBoot and SpringMVC Understand the differences and comparisons between SpringBoot and SpringMVC Dec 29, 2023 am 09:20 AM

Compare SpringBoot and SpringMVC and understand their differences. With the continuous development of Java development, the Spring framework has become the first choice for many developers and enterprises. In the Spring ecosystem, SpringBoot and SpringMVC are two very important components. Although they are both based on the Spring framework, there are some differences in functions and usage. This article will focus on comparing SpringBoot and Spring

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

What are the views in Word? What are the views in Word? Mar 19, 2024 pm 06:10 PM

I guess that many students want to learn the typesetting skills of Word, but the editor secretly tells you that before learning the typesetting skills, you need to understand the word views clearly. In Word2007, 5 views are provided for users to choose. These 5 views include pages. View, reading layout view, web layout view, outline view and normal view, let’s learn about these 5 word views with the editor today. 1. Page view Page view can display the appearance of the print result of the Word2007 document, which mainly includes headers, footers, graphic objects, column settings, page margins and other elements. It is the page view closest to the print result. 2. Reading layout view Reading layout view displays Word2007 documents and Office in the column style of a book

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles