Backbone.js Series Tutorial Five: backbone.events

Source: Internet
Author: User
Tags add object bind constructor contains extend functions string

Backbone.events Overview

The backbone.events object contains methods that help observer design patterns and a variable observer pattern that invokes pub/sub. These features allow different classes of objects (JavaScript objects) created by backbone to decouple from each other and communicate with each other. This is accomplished by extending (that is, _.extend (Model.prototype, backbone.events), the following constructors, and the functions used are all of the backbone.events:

    • Backbone.model ()
    • Backbone.collection ()
    • Backbone.view ()
    • Backbone.router ()
    • Backbone.history ()

If you still can't understand the observer design pattern and don't understand the concept of pub/sub terminology, think of the function in backbone.events as a $ ("" in JQuery). . On (), $ (""). Off (), $ (""). Trigger (), $ (""). One () method, which is to add a listening event for the DOM object of the native or custom event.

The backbone.events object contains the following functions, which create events, trigger events, and create a listener relationship between event-based objects.

    • On (event, callback, context) or bind ()
    • Off (event, callback, context) or Unbind ()
    • Trigger (event, arguments)
    • Once (event, callback, context)
    • Listento (Other object, event, callback)
    • Stoplistening (Other object, event, callback)
    • Listentoonce (Other object, event, callback)

In addition to extending the above constructor, thebackbone Namespace object itself is extended (_.extend (backbone, backbone.events); backbone.events Property, so the entire event system is available. For example, in the following example, I created a generic sayhi event and a eavesdropper object to listen for arbitrary sayhi events triggered on backbone objects.

 
 
    1. Add a custom event to the backbone object
    2. Backbone.on ("Sayhi", function () {
    3. Console.log ("Hi");
    4. });
    5. Create a Eavesdropper object that inherits objects with Backbone.events
    6. var eavesdropper = _.extend ({}, backbone.events);
    7. Enable Eavesdropper to listen for custom Sayhi events for backbone objects
    8. Eavesdropper.listento (Backbone, "Sayhi", function () {
    9. Console.log ("I heard that");
    10. });
    11. Trigger/Invoke Sayhi custom Event
    12. Backbone.trigger ("Sayhi"); Logs "Hi" and "I heard that"
    13. /* Remember that backbone inherits backbone namespaces through events
    14. (i.e. cause backbone did this: _.extend (backbone, backbone.events);) * *

Tips:

Note that I demonstrated the use of backbone.events in the backbone object above, but Backbone.events 's original intention was to inherit the backbone constructor mentioned earlier , and a model that allows decoupling communication is adopted.

Inheriting arbitrary objects with backbone.events

As mentioned earlier, the properties of thebackbone.events object and the backbone Namespace object are also infiltrated into the inheritance prototype chain of the backbone constructor. Therefore, you can inherit any object by using the functionality provided by the backbone.events object. Basically, backbone.events is a set of independent functions that can be mixed with any old JavaScript object. I will prove this by inheriting the a object first, and then verifying that the backbone.events method also has the attribute of a .

 
  
  
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. Verify that A is inherited by the Backbone.events method
  4. Console.log (Object.keys (A));
  5. * * Above log:
  6. [' Name ', ' on ', ' once ', ' off ', ' Trigger ', ' stoplistening ', ' listento ', ' listentoonce ', ' bind ', ' unbind ']
  7. */

Bind an Event object with on ()

The on () method binds a callback function to invoke an event trigger object. In the following code I bind a whatsmyname event to a object and then trigger the event.

 
  
   
  1. /using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. Add an event A to allow the callback function to be invoked when the event is triggered
  4. A.on ("Whatsmyname", function () {
  5. Console.log (this.name); This is A
  6. });
  7. Trigger Whatsmyname event in object A, log a
  8. A.trigger ("Whatsmyname");
  9. /* Reference the possibility of multiple events and callbacks through a single object on ()
  10. a.o{callback1:function () {}, Callback2:function ()});
  11. */

Tip: The use of a once (Event,callback,context) method is similar to the use of On (), except that once (Event,callback,context) events and callback functions are immediately deleted after the first call, So events and callbacks occur only once.

To bind multiple events with on ()

On () accepts a string parameter that can contain multiple events separated by a space. Next I add two events to a object, it calls the same function, and then I use two different event names to trigger the callback.

 
  
    
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. A.on ("Sayhi greet", function () {
  4. });
  5. Triggering sayhi and greet, Hello will be played two times on the console
  6. A.trigger ("Sayhi");
  7. A.trigger ("greet");

Namespace event on ()

You can add a space name after a named event name by using a colon. I have added two say events and a special space name to invoke events that use these name intervals.

 
  
     
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. A.on ("Say:hi", function () {
  4. });
  5. A.on ("Say:hello", function () {
  6. });
  7. Trigger Say:hi and Say:hello, note that I invoked two events with the same trigger.
  8. A.trigger ("Say:hi Say:hello");
  9. The following write cannot trigger two events at the same time
  10. A.trigger ("say");

Use trigger () to trigger and pass values to a callback function

The trigger () method is used to invoke a callback function named (that is, an event), which is widely used in this section. The second argument passed to the trigger () method is used to provide a pass value to the callback function. Below I trigger a callback function in A to pass a few values.

 
  
      
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. A.on ("Say", function (options) {
  4. Console.log (Options[0]);
  5. });
  6. Triggers the say event in a, passing two strings to the callback function in the same row
  7. A.trigger ("Say", ["Hello", "good Bye"]);

Tips:

    1. By providing a space-delimited string as the first argument in the trigger () list, you can simultaneously trigger multiple events that you want to invoke (that is, Obj.trigger ("Event1 event2 event3"); )。
    2. When an event is not actually defined on an object, it can also be triggered, and any object that listens to the event will be notified that the event has been triggered.

Use on () to set this to organize a callback function

The third argument passed to on () , which is to set the this text in the callback function. In the following code, I call a callback in a , but set the this value in the callback text to B.

 
  
       
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. var b = {name: "B"};
  4. When event A is invoked, set the callback text (this) to B
  5. A.on ("Saymyname", function () {
  6. Console.log (this.name);
  7. }, B);
  8. Trigger Saymyname
  9. A.trigger ("Saymyname"); Log B, because the callback text was modified

Removing events and callback functions with off ()

The off () method can be used to remove a single event, callback function, or all of the events from an object, usually with the following five uses.

1: Delete the named callback function

 
  
        
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. var foo = function () {
  4. Console.log ("foo");
  5. };
  6. var bar = function () {
  7. Console.log ("Bar");
  8. };
  9. A.on ("Log", Foo);
  10. A.on ("Log", bar);
  11. A.trigger ("Log"); Log background output foo and bar
  12. A.off ("Log", Foo); Delete Foo callback
  13. A.trigger ("Log"); Log background output bar only, because Foo was deleted

2: Delete the entire event of an object

 
  
         
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. var foo = function () {
  4. Console.log ("foo");
  5. };
  6. var bar = function () {
  7. Console.log ("Bar");
  8. };
  9. A.on ("Log", Foo);
  10. A.on ("Log", bar);
  11. A.trigger ("Log"); Log background output foo and bar
  12. A.off ("Log"); Delete Log Event
  13. A.trigger ("Log"); Log none because all log events have been deleted

3: Delete the same named callback function in all events

 
  
          
  1. Using the Backbone.events method to inherit a object
  2. var A = _.extend ({name: "A"}, backbone.events);
  3. var foo = function () {
  4. Console.log ("foo");
  5. };
  6. A.on ("Log1", foo);
  7. A.on ("log2", foo);
  8. A.trigger ("Log1 log2"); Log background output foo and foo
  9. A.off (Null,foo); Remove Foo callback for all events
  10. A.trigger ("Log1 log2"); Log none because all Foo callbacks have been deleted

4: Delete all events that contain specific text

 
  
           
  1. Inheriting B objects with the Backbone.events method
  2. var B = _.extend ({}, backbone.events);
  3. var C = {}
  4. B.on ("Logfoo", function () {
  5. Console.log ("foo");
  6. },C);
  7. B.on ("Logbar", function () {
  8. Console.log ("Bar");
  9. },C);
  10. B.trigger ("Logfoo logbar"); Log background output foo and bar
  11. B.off (NULL,NULL,C); Delete all events that contain C text
  12. B.trigger ("Logfoo logbar"); Log none, because all events containing C text have been deleted

5: Delete all events and callbacks for an object

 
  
            
  1. Inheriting B objects with the Backbone.events method
  2. var B = _.extend ({}, backbone.events);
  3. B.on ("Logfoo", function () {
  4. Console.log ("foo");
  5. });
  6. B.on ("Logbar", function () {
  7. Console.log ("Bar");
  8. });
  9. B.trigger ("Logfoo logbar"); Log background output foo and bar
  10. B.off (); Delete all events for B object
  11. B.trigger ("Logfoo logbar"); Log none because the events for all object B were deleted

Tips:

Use the off () function with no parameters on the backbone model, collection, view, or router object to remove all content in backbone events and callbacks.

Using Listento () to let object B Listen for events of object A

When the event of object A occurs, the Listento () method allows object B to monitor the event and invoke the callback function. In the following code, I let object B listen for the whoslisteningtome event that occurred on object A , which is called when the Whoslisteningtome event occurs Whoslisteningtome callback function.

 
  
             
  1. Inheriting objects A and object B with the Backbone.events method
 
  
              
  1. var A = _.extend ({name: "A"}, backbone.events);
  2. var B = _.extend ({name: "B"}, backbone.events);
  3. var whoslisteningtome = function () {
  4. Console.log (this.name);
  5. };
  6. Let object B listen for the Whoslisteningtome event that is triggered on object A, and then call Whoslisteningtome
  7. B.listento (A, "Whoslisteningtome", whoslisteningtome);
  8. A.trigger ("Whoslisteningtome"); Log B
  9. Object A has no Whoslisteningtome event, but this event can notify the listener that it has been triggered
  10. */

Tips:

    1. The listentoonce (other,callback,callback) method is available, similar to Listento (), except that listentoonce (other, the callback function of Callback,callback) is immediately removed after the first call, so the listener occurs only once.
    2. When an object event is triggered, no matter whether there is an event handler on the object, any other object that listens to the event can be notified that the event is triggered.

Use stoplistening () to stop one object from listening to all events on another object

When an object is listening to other objects, you can use the stoplistening () method to do the following four kinds of processing.

1: Stop all Listening

 
              
  1. var A = _.extend ({name: "A"}, backbone.events);
  2. var B = _.extend ({name: "B"}, backbone.events);
  3. var C = _.extend ({name: "C"}, backbone.events);
  4. var whoslisteningtome = function () {console.log (this.name);};
  5. Object B listens for Whoslisteningtome events for object A and object C
  6. B.listento (A, "Whoslisteningtome", whoslisteningtome);
  7. B.listento (C, "Whoslisteningtome", whoslisteningtome);
  8. Triggers the Whoslisteningtome event on object A and object C
  9. A.trigger ("Whoslisteningtome"); Logs B
  10. C.trigger ("Whoslisteningtome"); Logs B
  11. Let object B stop listening to all objects
  12. B.stoplistening ();
  13. Log None, because we let object B stop listening to all content
  14. A.trigger ("Whoslisteningtome");
  15. C.trigger ("Whoslisteningtome");

2: Stop listening to a particular object

 
              
    1. var A = _.extend ({name: "A"}, backbone.events);
    2. var B = _.extend ({name: "B"}, backbone.events);
    3. var C = _.extend ({name: "C"}, backbone.events);
    4. var whoslisteningtome = function () {console.log (this.name);};
    5. B.listento (A, "Whoslisteningtome", whoslisteningtome);
    6. B.listento (C, "Whoslisteningtome", whoslisteningtome);
    7. A.trigger ("Whoslisteningtome"); Log B
    8. C.trigger ("Whoslisteningtome"); Log B
    9. B.stoplistening (A);
    10. Because object B stops listening for object A, there is no background output, but object B continues to listen for object C
    11. A.trigger ("Whoslisteningtome");
    12. C.trigger ("Whoslisteningtome"); Log B

3: Stop listening to specific events on a particular object

 
  
               
  1. var A = _.extend ({name: "A"}, backbone.events);
  2. var B = _.extend ({name: "B"}, backbone.events);
  3. var whoslisteningtome = function () {console.log (this.name);};
  4. B.listento (A, "Whoslisteningtome", whoslisteningtome);
  5. A.trigger ("Whoslisteningtome"); Log B
  6. Let object B stop listening to a specific event on object a
  7. B.stoplistening (A, "whoslisteningtome");
  8. Log not, because object B stops listening to the Whoslisteningtome event on object A
  9. A.trigger ("Whoslisteningtome");

4: Stop listening to a specific event and callback on a particular object

 
  
                
  1. var A = _.extend ({name: "A"}, backbone.events);
  2. var B = _.extend ({name: "B"}, backbone.events);
  3.  
  4. var whoslisteningtome = function () {console.log (this.name);};
  5. var whoslisteningtomeagain = function () {console.log (this.name);};
  6.  
  7. b.listento (A, "Whoslisteningtome", whoslisteningtome);
  8. b.listento (A, "Whoslisteningtome", whoslisteningtomeagain);
  9.  
  10. a.trigger ("Whoslisteningtome");//log spool output B and B
  11.  
  12. //let object B stop listening to specific events and callbacks on object a
  13. b.stoplistening (A, "Whoslisteningtome", whoslisteningtomeagain);
  14.  
  15. a.trigger ("Whoslisteningtome");//log B

Backbone Embedded Event

Backbone triggers the following internal events that embed models, collections, views, and router objects, so we pass the on () of the backbone event and Listento () method can use these events, and have a variety of ways to use. But for now, let's take a look at the individual event descriptions in the table below to get a clearer idea of where the event is triggered.

model, collection, view, router , and historical object events

Collection Object Events

Model Object Events

Model or Collection Object events

Router Object events

The above mentioned events, in addition to the ' all ' type events, can be found in this section to specify in what circumstances the event on the object is triggered. To better grasp the backbone embedding event, we will detail the ' all ' event below. The backbone embedded event is triggered by the backbone object, and once any event on backbone model, collection, view, or router is triggered, the ' all ' event is triggered/broadcast.

In the following example I will demonstrate a backbone model and bind a callback function on the ' All ' event with on () . Then you set some data in the model, and the model broadcasts two events: a change event and a ' Change:attribute event (described in the table above). The ' All event is triggered two times, because when two ' change ' events are triggered, the ' all ' event is broadcast two times.

 
  
                 
  1. To create a default model object
  2. var MyModel = new Backbone.model ();
  3. Bind a callback object to the embedded "all" event
  4. Mymodel.on ("All", function (e) {
  5. Console.log (e);
  6. });
  7. Triggers the ' change ' and ' change:attribute ' events and triggers all two times
  8. * * Use Listento () to achieve the same effect
  9. var A = _.extend ({}, backbone.events);
  10. A.listento (MyModel, "All", function (e) {
  11. Console.log (e);
  12. });
  13. */

As mentioned in the 1th of this section, the all event is able to capture who triggered the ' all ' event, so we can log to (log) which event triggered the ' all ' event.

Note that the' all ' event is not only for the model, it can be triggered by arbitrarily triggered backbone inline events. However, the ' Change ' event is specifically targeted at the model. This example helps to understand the broad understanding of how to use all embedded events during the development of backbone applications.

Backbone.events Summary

The idea from this section is to use the common pattern of backbone objects to communicate with each other, using the above methods to handle JavaScript objects, and you can learn how to create custom events and better handle backbone Models, collections, Views, and the events that are triggered in the Router .



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.