`
since1027
  • 浏览: 9302 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Part 8: Understanding Backbone.js Events

阅读更多
In this article, we will look at events in Backbone.js. We will see how backbone provides us events and how we can use backbone events in our application.

Background

Events are a vital part of any application framework. Events are useful mainly in two scenarios when it comes to applications. Events can be particularly very useful when we want to implement a publisher subscriber model in our application where any change in one area of application(the publisher) will trigger a notification to everyone who is interested(subscribers).

There are a plethora of JavaScript libraries that can be used to implement eventing in our JavaScript application. Backbone also provides a very nice implementation of eventing mechanism which makes the use of publisher subscriber model in our application seamless. Let us now look at how we can use events in a backbone application.

Link to complete series:


Using the code

Backbone provides a very simple, clean and elegant way to use events. What backbone does is that it let any object to be associated with backbone events simply by extending from the Backbone.Events. This can be done by calling _.extend method on the object instance. Let us create a simple object that extends from Backbone.Event.

var testObj = {};
_.extend(testObj, Backbone.Events);

Once we have extended from Backbone.Event, we can use onto hook the callback functions with the event. Lets define a simple function and subscribe to an event.

function ShowMeWhenSomethingHappens(message) {
    alert(message);
}

testObj.on('something', ShowMeWhenSomethingHappens);

Now the simplest way to invoke this event is by calling the triggeron the event name. Lets invoke the function and see the results.

testObj.trigger('something', 'Hello events');




So we can see how simple it is to use triggers with backbone. Or is it? The only pain point I see in this event mechanism is the hookup of Backbone events with objects using _.extend. Fortunately, we don’t have to call this extend to hook backbone eventing mechanism with any object. If we have an object that extends from a backbone type i.e. model, view, collection then we have the event mechanism hooked with it by default. So lets say of we have a simple model like following.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    }
});

It if already hooked with the backbone events. So if if I run the following code, it should just work fine and show us the alert like the previous code.

var book = new Book();

book.on('something', ShowMeWhenSomethingHappens);

book.trigger('something', 'Hello events - backbone model');




In the same way events can be used with any of the backbone object seamlessly. Let us now look at the functions that can be used to take full control over these events. The first function that is of interest to us is on. onattaches a callback function with an event.

var book = new Book();
book.on('something', ShowMeWhenSomethingHappens);

The callback functions that are attached to an event using onfunction can be removed by using off. So if we want to remove the callback function attached to the event in the previous step, we just have to use the offfunction.

book.off('something', ShowMeWhenSomethingHappens);

If we want to associate a callback with an event that should only be called once, we can use once.

book.once('something', ShowMeWhenSomethingHappens);

And finally, how can we trigger an event? The events can be triggered by using the triggerfunction.

book.trigger('something', 'Hello events - backbone model');

These are the basic functions that we can use to subscribe to events. The important thing to note here is that these functions are being used on the object that is publishing the events. What if we want to use another object i.e. the subscriber then there is another set of functions that we can use. Before looking at the function lets try to understand this scenario better. Lets say I have another model Catalogin my application.

var Catalog = Backbone.Model.extend({
    defaults: {
        ID: "",
        CatalogName: ""
    },

    // code ommitted for brevity

    bookChanged : function(book) {
        alert(book.get("BookName"));
    }
});

What this model is expecting is that whenever a book is changed, the bookChangedfunction will get called. One way to do that is by using the on function as:

var catalog = new Catalog();

var book = new Book({BookName : "test book1"});                

book.on('changed', catalog.bookChanged);

book.trigger('changed', book);

Another way to perform the same thing is by using the event association functions on the subscriber i.e. the catalog object. To achieve this, we need to use the listenTofunction. Lets see how this can be done.

var catalog = new Catalog();

var book = new Book({BookName : "test book1"});                

catalog.listenTo(book, 'changed', catalog.bookChanged);

book.trigger('changed', book);




In the above code, we are still subscribing the catalog object with the book’s event but using listenTofunction on the catalog object instead. If we want to remove the associated object the we can use the stopListeningfunction.

catalog.stopListening(book);

If we want the equivalnt of once in this scenario, we can use listenToOncefunction instead.

catalog.listenToOnce(book, 'changed', catalog.bookChanged);

The benefit of using these set of functions over the previously shown one is that the subscribers can keep track of the all the events they are subscribed to and then selectively add and remove their subscriptions.

Note. The above code example is very contrived and far from the real world example. Its only purpose is to show how the given set of functions work.

There are a lot of build in events that backbone framework triggers that we can subscribe to in our application. For example “ change” will be triggered on a model when its state is changed. “ add” and “ remove” will be called whenever an item is added or removed from the collection respectively. There are a lot of such built in events that the framework triggers on models, view, collections and routes. I recommend referring the backbone documentation for the exhaustive list.

Point of interest

In this small article we looked at events in backbone. How backbone makes it extremely easy to work with events and how it provides a lot of built in events that can readily be subscribed from the application. This article has been written from a beginner’s perspective. I hope this has been informative.

原文链接:http://rahulrajatsingh.com/2015/02/backbone-tutorial-part-8-understanding-backbone-js-events/
分享到:
评论
1 楼 since1027 2016-06-23  
Backbone系列教程的最后一章了,希望对Backbone入门者有所帮助

相关推荐

    TODO-APP:使用Backbone.js开发ud989的项目

    Backbone.js 是一个轻量级的JavaScript库,它为Web应用提供了模型-视图-控制器(MVC)架构模式。在"TODO-APP: 使用Backbone.js开发ud989的项目"中,我们将深入探讨如何利用Backbone.js构建一个待办事项应用。 **一...

    singool:基于Backbone.js的框架,用于开发单页Web应用程序

    Backbone.js是一个JavaScript库,它提供了模型-视图-控制器(MVC)架构模式,帮助开发者组织代码,使得前端开发更加有序和高效。它强调数据模型和视图的绑定,以及事件驱动的编程方式。 Singool.js框架在其基础上...

    Backbone.js(1.1.2) API中文文档.zip Backbone.js离线文档

    Backbone.js是一款轻量级的JavaScript库,专为构建丰富的Web应用程序而设计。它通过提供模型(Models)、视图(Views)、集合(Collections)和路由器(Routers)等核心概念,帮助开发者组织代码并实现MVC(Model-...

    Backbone.js开发秘笈源码

    Backbone.js 是一个轻量级的JavaScript库,主要用于构建可维护性和结构化的Web应用。它提供了一套模型-视图-控制器(MVC)架构,帮助开发者组织代码,使得前端开发更加有序。在深入探讨Backbone.js的开发秘笈源码...

    backbone.js入门教程

    Backbone.js 是一款轻量级的 JavaScript 框架,它为 Web 开发提供了 MVC(Model-View-Controller)架构的基础组件。该框架的目标是简化客户端应用的开发流程,通过提供 Models、Collections 和 Views 的抽象层次结构...

    BACKBONE.JS应用程序开发

    backbone.js提供了一套web开发的框架,为复杂javascript应用程序提供一个mvc结构。, 《backbone.js应用程序开发》详细介绍了如何使用backbone.js完成web应用开发。全书从了解mvc、spa和backbone.js的基本知识开始,...

    Backbone.js应用程序开发 中文清晰完整版pdf

    backbone.js提供了一套web开发的框架,为复杂javascript应用程序提供一个mvc结构。 《backbone.js应用程序开发》详细介绍了如何使用backbone.js完成web应用开发。全书从了解mvc、spa和backbone.js的基本知识开始,...

    Developing Backbone.js Applications

    5. **视图事件(Events)**:Backbone.js提供了一个事件系统,允许视图与其他对象进行通信。这有助于减少对象之间的耦合,使得代码更易于理解和维护。 **Backbone.js的使用场景** Backbone.js适用于那些需要在客户端...

    Backbone.js的事件绑定

    Backbone.js是一个轻量级的JavaScript库,专为构建可维护和模块化的Web应用而设计。它基于MVC(Model-View-Controller)模式,帮助开发者组织和管理前端代码结构,使得复杂的应用程序更容易理解和扩展。在“Backbone...

    《Backbone.js实战》(陶国荣)源码

    Backbone.js是一款轻量级的JavaScript库,专为构建复杂的Web应用而设计。它通过提供模型、视图、集合和路由器等概念,帮助开发者更好地组织和管理代码,实现MVC(Model-View-Controller)模式在前端的落地。陶国荣的...

    Backbone.js实战.zip

    Backbone.js是一款轻量级的JavaScript库,专为构建可维护性和结构化的Web应用而设计。它主要关注数据模型的管理、视图的渲染以及URL路由,为前端开发提供了强大的框架支持。本资源是关于"Backbone.js实战"的电子书,...

    backbone.js.zip

    Backbone.js是一个轻量级的JavaScript库,专为构建可维护和组织良好的前端应用程序而设计。这个库的核心理念是提供模型-视图-控制器(MVC)架构模式,帮助开发者在浏览器端更好地组织代码,提高代码复用性和可扩展性...

    Pro Single Page Application Development - Using Backbone.Js and ASP.Net.2014

    Pro Single Page Application Development - Using Backbone.Js and ASP.Net by Gil Fink and Ido Flatow.2014

    BACKBONE.JS应用程序开发--高清版

    Backbone.js提供了一套Web开发的框架,为复杂的JavaScript应用程序提供了一个MVC结构。  《Backbone.js应用程序开发》详细介绍了如何使用Backbone.js完成Web应用开发。全书从了解MVC、SPA和Backbone.js的基本知识...

    前端项目-backbone.radio.zip

    1. **Backbone.js框架**:Backbone.js是一个轻量级的JavaScript库,它为构建单页应用(SPA)提供了模型-视图-视图模型(MVVM)的架构模式,帮助开发者组织代码结构。 2. **Backbone.Radio**:Backbone.Radio是...

    用Backbone.js写的小项目

    8. **模块化和组织结构**: 为了保持代码的清晰和可维护性,Backbone.js项目通常会采用模块化的方式组织代码,每个模块对应一个单独的JavaScript文件,比如Model、View、Router等。这样的组织结构使得代码更容易理解...

    backbone.js underscore.js

    Backbone.js 和 Underscore.js 是两个在JavaScript开发中广泛使用的库,它们为构建复杂的Web应用程序提供了强大的工具。这两个库都是基于jQuery库,其中jQuery-1.10.2.js是jQuery的一个版本,它为DOM操作、事件处理...

Global site tag (gtag.js) - Google Analytics