Importance of Events

Whether this is an obvious question or not, events in javascript and the type of events are crucial to any website. They also allow the control of flow through events at the programmers liking.

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments.


Types of Events

on

object.on(event, callback, [context])

this binds a callback function to an object. This callback will be invoked whenever the event is fired.

off

object.off([event], [callback], [context])

Will remove a previously bounded callback function from an object. Things to keep in mind. If no context is given for the specific callback are given when calling off then all callbacks will be removed pertaining to this object. In a similar fashion if no callback is specified when passing off all callbacks for this object will be removed.

trigger

object.trigger(event, [*args])

This trigger callbacks for the given event or any list of event passed. The arguments specified to trigger will then be passed along to the vent callbacks.

once

object.once(event, callback, [context])

this event method is very similar to that of on. However, as its name implies it will bound the callback to fire only once and then will be unbound. It is a very powerful tool if you want a specific event to be bound only once in a program and then have it removed.

listenTo

object.listenTo(other, event, callback)

This method tell one particular object (the first one) to “listen to” a particular even of a different object. This has it advantages instead of calling on for an object since it will allow the object to be aware of the events of another object.

stopListening 

object.stopListening([other], [event], [callback])

As the name may have implied it unbinds listenTo from a specific object. You have the option of not passing in any arguments which will tell the object to stop listening to all events. However, you may pass along particular arguments to tell this objects to only stop listening  to a select amount of events of another object.

listenToOnce

object.listenToOnce(other, event, callback)

Exactly like once it will bind listenTo to an object. It will then only fire once as specified and then remove itself from the object.

 


 

There are several other built in Backbone.js events which are cataloged. You even have the option of specifying your own events which you can also see here:

Backbone.js Events