


Examples to explain the View view in the Backbone.js framework of JavaScript_Basic knowledge
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 .
<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 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中的事件都是有效的。
(如果你對jQuery比較熟悉,可能了解它所提供的delegate()方法。該方法實際上將事件綁定在父層元素,然後在事件冒泡過程中,透過檢查目標子元素來觸發事件。)
視圖物件透過delegate()方法綁定事件,表示我們不需要關心視圖結構變化對事件產生的影響,同時也說明events中選擇器所對應的元素必須處於視圖的el元素之內,否則綁定的事件是無法生效的。
儘管如此,有些情況下可能我們仍然需要手動綁定和解除事件,視圖對象提供了delegateEvents()和undelegateEvents()方法用於動態綁定和解除events事件列表,你可以通過查看API文檔來了解它們。
渲染視圖與資料
視圖主要用於介面事件的綁定和資料渲染,然而視圖物件僅僅提供了一個和渲染相關的方法render(),並且它是一個沒有任何邏輯、也沒有任何地方引用到的空方法,我們需要重載它來實現自己的渲染邏輯。
視圖中可能包含許多介面邏輯,這裡建議所有的視圖子類別都重載render()方法,並將它作為最終渲染的入口方法。在團隊開發中,嚴格遵守規範編碼可以幫助別人更好地理解和維護你的程式碼。

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)
