- 浏览: 10251 次
- 性别:
- 来自: 南京
-
最新评论
-
since1027:
Backbone系列教程的最后一章了,希望对Backbone入 ...
Part 8: Understanding Backbone.js Events
In this article, we will try to look at the View classes in Backbone.js and see how view classes help us in updating the relevant parts of the application easily.
Background
The biggest problem while writing JavaScript applications is the spaghetti code that one needs to write just for HTML DOM manipulation. Every element on the UI will need some actions to happen when the user interacts with them. Some UI elements would want to automatically update the values based on the new/updated data. Doing all this using plain HTML and JavaScript/jQuery is a big problem (doable but nightmare) specially from maintenance perspective.
Backbone.js view greatly helps us when it comes to creating large scale manageable applications. The view classes are more like a glue that holds an HTML template with the model object. Also, this provides the mechanism to handle the events raised from the model and update the UI and handle UI events and act on them (perform some operations on the model). So in a way we can say that the views are just observers who are listening to the model and UI events which makes them a perfect place to handle all the events and act upon them. Backbone views can be thought of as:
Observers that keep listening to the DOM events and in case the event fires taking the appropriate actions.
Objects backed by models that are responsible for rendering the model data on the screen.
Let us see how we can use backbone.js views to efficiently manage the applications.
Link to complete series:
Using the code
Creating a simple view
Let is start the discussion by looking at how we can create backbone views. Like backbone models and collections, creating a backbone view is also as easy as extending the existing Viewclass of backbone.
Like models and collections, we can also override the initialize and constructor of the backbone views. Lets try to see how we can override the initializefunction.
Instantiating the view is also straight forward. A view can simply be instantiated using the newkeyword.
Associating model with a view
Every view will be backed by a model. This modelcan be passed to the view in the constructor.
This model can either be a backbone model or a backbone collection. The view can extract the information from its model and render the HTML accordingly.
Understanding the el property
Now we are saying that the views are responsible for listening to DOM element’s events and also for updating the DOM elements. For this to happen the view class should be associated/attached to a DOM element. Backbone views are always associated to a DOM element. This associated DOM element can be accessed/manipulated using the elproperty.
Now there are 2 ways to create view:
1.Creating a view that will get associated with an existing DOM element.
2.Creating a view that will create its own DOM element on the fly.
So lets start by looking at how we can create a view that will get associated with an existing DOM element. The views constructor is capable of accepting a lot of parameters. It can accept models, collections and even the DOM element that this view should associate itself to.
Lets say we want to create a view for an existing DOM element i.e. a div with id="sampleDiv".
When we run the application and try to watch the elproperty, we can see that the el property contains the div element.
Now lets see how we can create a view that will create a DOM element for it dynamically. The way it works is that we can specify tagName, className, id and attributes in a backbone view. Based on these values the el will be created by backbone. Lets try to create a simple div with id using this approach.
When we create this view, we can see that the view is associated with a div which was created using our specified tagName and id values.
Now these two approached provides a lot of flexibility while developing backbone applications. Let us try to look at a simple example to understand the complete picture. lets say we need to create a list of books. We know the area where these items should be rendered but we the actual items will be added at runtime. This can easily be achieved by creating an empty list and using JavaScript to add list items at runtime. Lets see how we can use backbone views to achieve this.
First let us create the a simple view that will render the book data as a list element. Do do this we will use the dynamically generated DOM element.
What this view is doing is that, it is overiding the render function to render the book name in a list element. We have overridden the renderfunction to render the book as a list element.
Now we need a view that will contain this list elements i.e. the list view. For this lets create a simple list element on my HTML and then lets use this view class to use that el.
What this view is doing is that, it is accepting a collection of books and in the render function it is using the bookViewto render the books inside the associated el. Now the next thing we need to do is to associated the list created on the HTML page with this view as its el and pass the books collection to this view as model.
Calling the render function of this view will use our backbone views and render the list of books in an unordered list.
Note: A view’s elcan be changed anytime by calling the setElementmethod of the view.
Using templates
Now in our example we have overridden the render function of our views and took charge of rendering the HTML is our own code. This is still better than plain JavaScript/jquery based approach because here our JavaScript code is not intermingled with HTML and there is a logical structure to our views.
But the problem is that our view HTML could become very complex and it might always not be possible to spit out that HTML from our render functions. To ease this problem backbone supports view templates. Any template engine can be used with backbone view. To understand the concept of templates, let us use the simple JavaScript style templates.
Lets say that every book needs to be rendered as a drop down menu. This can be achived by using bootstrap very easily. But creating all that HTML in the render function might not be a very good idea. So let us create one more set of views that will use the template to render the books in a drop-down.
And the template is defined in the HTML file itself as:
What will happen here is that the bookView2will use this template to render the books as list elements. Backbone can work on any view engine. Also the example taken here was little contrived but very complex templates can also be created and rendered using this approach very easily.
Listening to DOM events
Now there is one important thing remaining. how can a view object listen to DOM elements and perform needed actions. To understand this let us add a simple button on our list view and try to listen to its click action.
Now whenever an a DOM element raises an event the associated view will look for its handler in the events section. If the handler exists, it calls that handler. this is very useful when we need to listen to DOM events and take some actions. we can use {"event selector": "callback"}format to declare our DOM event handlers. the selector are are usual jquery/css selectors.
Listening to Model changes
In large scale applications there might be multiple views rendering the same data. what if one view changes the data? should other views continue to show the stale data? Probably no. Thus we also need to listen to the model changes too. this can easily be achieved by listening to model changes as:
What we did here is that whenever new books are added to the collection. The associated view will be listening to the add event. On recieving this event it will simply renders the view again. This can be tested by simply adding few more books in the already rendering collection
On same lines, we can also listen to change event to listen to model updates.
To test this, lets just try to update a book that is already being rendered on screen.
Removing a view from DOM
Removing a view from DOM can be easily achieved by calling the remove function on the view.
Point of interest
In this article we looked at the backbone views. We looked at how we can use backbone views to implement better structured applications that can easily perform DOM manipulations.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-6-understanding-backbone-js-views/
Background
The biggest problem while writing JavaScript applications is the spaghetti code that one needs to write just for HTML DOM manipulation. Every element on the UI will need some actions to happen when the user interacts with them. Some UI elements would want to automatically update the values based on the new/updated data. Doing all this using plain HTML and JavaScript/jQuery is a big problem (doable but nightmare) specially from maintenance perspective.
Backbone.js view greatly helps us when it comes to creating large scale manageable applications. The view classes are more like a glue that holds an HTML template with the model object. Also, this provides the mechanism to handle the events raised from the model and update the UI and handle UI events and act on them (perform some operations on the model). So in a way we can say that the views are just observers who are listening to the model and UI events which makes them a perfect place to handle all the events and act upon them. Backbone views can be thought of as:
Observers that keep listening to the DOM events and in case the event fires taking the appropriate actions.
Objects backed by models that are responsible for rendering the model data on the screen.
Let us see how we can use backbone.js views to efficiently manage the applications.
Link to complete series:
- Part 1: Introduction to Backbone.Js
- Part 2: Understanding the basics of Backbone Models
- Part 3: More about Backbone Models
- Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
- Part 5: Understanding Backbone.js Collections
- Part 6: Understanding Backbone.js Views
- Part 7: Understanding Backbone.js Routes and History
- Part 8: Understanding Backbone.js Events
Using the code
Creating a simple view
Let is start the discussion by looking at how we can create backbone views. Like backbone models and collections, creating a backbone view is also as easy as extending the existing Viewclass of backbone.
var sampleView = Backbone.View.extend({ });
Like models and collections, we can also override the initialize and constructor of the backbone views. Lets try to see how we can override the initializefunction.
var sampleView = Backbone.View.extend({ initialize: function() { console.log('sampleView has been created'); } });
Instantiating the view is also straight forward. A view can simply be instantiated using the newkeyword.
var view1 = new sampleView();
Associating model with a view
Every view will be backed by a model. This modelcan be passed to the view in the constructor.
var book1 = new Book({ ID: 1, BookName: "Book 1" }); var m_bookView = new bookView({model: book1});
This model can either be a backbone model or a backbone collection. The view can extract the information from its model and render the HTML accordingly.
Understanding the el property
Now we are saying that the views are responsible for listening to DOM element’s events and also for updating the DOM elements. For this to happen the view class should be associated/attached to a DOM element. Backbone views are always associated to a DOM element. This associated DOM element can be accessed/manipulated using the elproperty.
Now there are 2 ways to create view:
1.Creating a view that will get associated with an existing DOM element.
2.Creating a view that will create its own DOM element on the fly.
So lets start by looking at how we can create a view that will get associated with an existing DOM element. The views constructor is capable of accepting a lot of parameters. It can accept models, collections and even the DOM element that this view should associate itself to.
Lets say we want to create a view for an existing DOM element i.e. a div with id="sampleDiv".
var view1 = new sampleView({ el: $("#sampleDiv") });
When we run the application and try to watch the elproperty, we can see that the el property contains the div element.

Now lets see how we can create a view that will create a DOM element for it dynamically. The way it works is that we can specify tagName, className, id and attributes in a backbone view. Based on these values the el will be created by backbone. Lets try to create a simple div with id using this approach.
var sampleView2 = Backbone.View.extend({ tagname: 'div', id: 'sampleDiv' });
When we create this view, we can see that the view is associated with a div which was created using our specified tagName and id values.

Now these two approached provides a lot of flexibility while developing backbone applications. Let us try to look at a simple example to understand the complete picture. lets say we need to create a list of books. We know the area where these items should be rendered but we the actual items will be added at runtime. This can easily be achieved by creating an empty list and using JavaScript to add list items at runtime. Lets see how we can use backbone views to achieve this.
First let us create the a simple view that will render the book data as a list element. Do do this we will use the dynamically generated DOM element.
var bookView = Backbone.View.extend({ tagname: "li", model: Book, render: function (){ this.$el.html('<li>' + this.model.get("BookName") + '</li>'); return this; } });
What this view is doing is that, it is overiding the render function to render the book name in a list element. We have overridden the renderfunction to render the book as a list element.
Now we need a view that will contain this list elements i.e. the list view. For this lets create a simple list element on my HTML and then lets use this view class to use that el.
var bookListView = Backbone.View.extend({ model: BooksCollection, render: function() { this.$el.html(); // lets render this view var self = this; for(var i = 0; i < this.model.length; ++i) { // lets create a book view to render var m_bookView = new bookView({model: this.model.at(i)}); // lets add this book view to this list view this.$el.append(m_bookView.$el); m_bookView.render(); // lets render the book } return this; }, });
What this view is doing is that, it is accepting a collection of books and in the render function it is using the bookViewto render the books inside the associated el. Now the next thing we need to do is to associated the list created on the HTML page with this view as its el and pass the books collection to this view as model.
var book1 = new Book({ ID: 1, BookName: "Book 1" }); var book2 = new Book({ ID: 2, BookName: "Book 2" }); var book3 = new Book({ ID: 3, BookName: "Book 3" }); var book4 = new Book({ ID: 4, BookName: "Book 4" }); var book5 = new Book({ ID: 5, BookName: "Book 5" }); var bookCollection = new BooksCollection([book1, book2, book3, book4, book5]); var bookList = null; $(document).ready(function () { bookList = new bookListView({ el: $("#bookList"), model: bookCollection }); bookList.render(); });
Calling the render function of this view will use our backbone views and render the list of books in an unordered list.

Note: A view’s elcan be changed anytime by calling the setElementmethod of the view.
Using templates
Now in our example we have overridden the render function of our views and took charge of rendering the HTML is our own code. This is still better than plain JavaScript/jquery based approach because here our JavaScript code is not intermingled with HTML and there is a logical structure to our views.
But the problem is that our view HTML could become very complex and it might always not be possible to spit out that HTML from our render functions. To ease this problem backbone supports view templates. Any template engine can be used with backbone view. To understand the concept of templates, let us use the simple JavaScript style templates.
Lets say that every book needs to be rendered as a drop down menu. This can be achived by using bootstrap very easily. But creating all that HTML in the render function might not be a very good idea. So let us create one more set of views that will use the template to render the books in a drop-down.
var bookView2 = Backbone.View.extend({ model: Book, tagName: 'li', template: '', initialize: function() { this.template = _.template($('#bookItem').html()); }, render: function() { this.$el.html(this.template(this.model.attributes)); return this; } }); var bookListView2 = Backbone.View.extend({ model: BooksCollection, render: function() { this.$el.html(); // lets render this view for(var i = 0; i < this.model.length; ++i) { // lets create a book view to render var m_bookView = new bookView2({model: this.model.at(i)}); // lets add this book view to this list view this.$el.append(m_bookView.$el); m_bookView.render(); // lets render the book } return this; }, });
And the template is defined in the HTML file itself as:
<script type="text/template" id="bookItem"> <li role="presentation"><a role="menuitem" tabindex="-1" href="#"> <%= BookName %> </a></li> </script>

What will happen here is that the bookView2will use this template to render the books as list elements. Backbone can work on any view engine. Also the example taken here was little contrived but very complex templates can also be created and rendered using this approach very easily.
Listening to DOM events
Now there is one important thing remaining. how can a view object listen to DOM elements and perform needed actions. To understand this let us add a simple button on our list view and try to listen to its click action.
var bookView2 = Backbone.View.extend({ model: Book, tagName: 'li', template: '', events: { 'click': "itemClicked" }, itemClicked: function () { alert('clicked: ' + this.model.get('BookName')); }, initialize: function() { this.template = _.template($('#bookItem').html()); }, render: function() { this.$el.html(this.template(this.model.attributes)); return this; } });
Now whenever an a DOM element raises an event the associated view will look for its handler in the events section. If the handler exists, it calls that handler. this is very useful when we need to listen to DOM events and take some actions. we can use {"event selector": "callback"}format to declare our DOM event handlers. the selector are are usual jquery/css selectors.
Listening to Model changes
In large scale applications there might be multiple views rendering the same data. what if one view changes the data? should other views continue to show the stale data? Probably no. Thus we also need to listen to the model changes too. this can easily be achieved by listening to model changes as:
var bookListView = Backbone.View.extend({ model: BooksCollection, initialize: function() { // lets listen to model change and update ourselves this.listenTo(this.model, "add", this.modelUpdated); }, modelUpdated: function() { this.render(); }, });
What we did here is that whenever new books are added to the collection. The associated view will be listening to the add event. On recieving this event it will simply renders the view again. This can be tested by simply adding few more books in the already rendering collection
function AddMoreBooks() { var i = bookCollection.length + 1; var newBook = new Book({ID: i, BookName: 'yet another book_' + i}); bookCollection.add(newBook); }

On same lines, we can also listen to change event to listen to model updates.
var bookView = Backbone.View.extend({ tagName: "li", model: Book, initialize: function() { // lets listen to model change and update ourselves this.listenTo(this.model, "change", this.render); } });
To test this, lets just try to update a book that is already being rendered on screen.
book1.set('BookName', book1.get('BookName') + '_updated');

Removing a view from DOM
Removing a view from DOM can be easily achieved by calling the remove function on the view.
bookList.remove();
Point of interest
In this article we looked at the backbone views. We looked at how we can use backbone views to implement better structured applications that can easily perform DOM manipulations.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-6-understanding-backbone-js-views/
- backboneViewsSample.zip (323.1 KB)
- 下载次数: 0
发表评论
-
Part 8: Understanding Backbone.js Events
2016-06-22 10:34 860In this article, we will look a ... -
Part 7: Understanding Backbone.js Routes and History
2016-06-22 09:52 607In this article, we will try to ... -
Part 5: Understanding Backbone.js Collections
2016-06-21 14:39 687In this article we will discuss ... -
Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
2016-06-21 14:21 982In this article we will discuss ... -
Part 3: More about Backbone Models
2016-06-21 14:08 836In this article we will look at ... -
Part 2: Understanding the basics of Backbone Models
2016-06-21 12:55 730When we talk about any MV* patt ... -
Part 1: Introduction to Backbone.Js
2016-06-21 11:12 759It was a long time ago (almost ...
相关推荐
在IT行业中,Backbone.js是一个非常重要的JavaScript库,它为构建复杂的Web应用程序提供了一种结构化的方法。在本文中,我们将深入理解Backbone Models的基本概念,这是Backbone框架的核心组件之一。 **Backbone ...
Cocoa Frameworks: The Backbone of Your App Creating Views Programmatically Strings, Text, and Fonts Get More from Interface Buillder Drawing on the Strength of Core Graphics Moving to Core Animation ...
javaee电子商城系统课程设计样本.doc
scratch少儿编程逻辑思维游戏源码-糖果大爆险.zip
# 压缩文件中包含: 中文-英文对照文档 jar包下载地址 Maven依赖 Gradle依赖 源代码下载地址 # 本文件关键字: jar中文-英文对照文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件;
# 压缩文件中包含: 中文-英文对照文档 jar包下载地址 Maven依赖 Gradle依赖 源代码下载地址 # 本文件关键字: jar中文-英文对照文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件;
GIS安装施工综合方案.doc
内容概要:本文详细介绍了选题系统源码,涵盖PHP、CSS、JavaScript和MySQL四种核心技术。系统采用B/S架构,支持管理员、审核员、教师和学生四种身份登录,每种身份有独立的功能权限。文中提供了详细的环境搭建指南,如使用phpStudy和Navicat进行项目管理和数据库操作。此外,还展示了关键代码片段,如登录验证、权限管理、数据库设计以及界面优化方法。同时,针对性能优化提出了建议,如解决N+1查询问题的方法。 适合人群:适用于有一定编程基础,尤其是对PHP和Web开发感兴趣的开发者和技术爱好者。 使用场景及目标:① 学习并掌握B/S架构的应用开发流程;② 实践多角色登录和权限管理的具体实现;③ 提升Web应用的界面优化和用户体验;④ 掌握数据库设计和性能优化技巧。 其他说明:本文不仅提供了完整的代码示例,还包括了详细的开发文档和支持材料,帮助读者快速上手并深入理解整个项目的构建过程。
scratch少儿编程逻辑思维游戏源码-下水道冒险猫.zip
scratch少儿编程逻辑思维游戏源码-下雨时向北的路.zip
内容概要:本文深入探讨了三相下垂双逆变器同步并联控制技术,重点介绍了下垂控制的基本原理及其在微电网中的应用。文章详细解释了下垂控制如何通过调整频率和电压幅值来实现负载的自动分配,并讨论了在多台逆变器并联时可能出现的环流问题以及解决方案,如虚拟阻抗法。此外,还介绍了同步环节的关键技术,特别是改进型锁相环的应用,并提供了具体的实现代码示例。最后,文章分享了一些实用的调试技巧和经验,强调了参数整定的重要性。 适用人群:从事电力电子、微电网控制领域的研究人员和技术人员。 使用场景及目标:适用于希望深入了解三相下垂双逆变器同步并联控制技术的工程师和科研人员,旨在帮助他们掌握核心技术,解决实际工程中的问题。 其他说明:文中提供的代码示例和调试方法有助于读者更好地理解和应用相关技术,提高系统的稳定性和性能。
# 压缩文件中包含: 中文-英文对照文档 jar包下载地址 Maven依赖 Gradle依赖 源代码下载地址 # 本文件关键字: jar中文-英文对照文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件;
GEPLC机组自动化装置编程使用说明书.doc
scratch少儿编程逻辑思维游戏源码-我的领土.zip
# 压缩文件中包含: 中文文档 jar包下载地址 Maven依赖 Gradle依赖 源代码下载地址 # 本文件关键字: jar中文文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件;
scratch少儿编程逻辑思维游戏源码-我的世界 MMO V1.6.zip
scratch少儿编程逻辑思维游戏源码-坦克(1).zip
GSM移动通信网容量解决方案.doc
scratch少儿编程逻辑思维游戏源码-天台狂飙.zip
scratch少儿编程逻辑思维游戏源码-逃避猫 避险闯关游戏.zip