Backbone.js on Event
Last Updated :
10 Jul, 2022
Backbone.js on Event is used to bind a callback function to an object. When an event is triggered, the callback is invoked. If there are large numbers of events on a page then the convention is to use colons to namespace each event:
"poll:start", or "change:selection"
Syntax:
object.on(event, callback, [context] );
Callbacks that are bound to a special event “all” is triggered whenever any event occurs and the name of the event is passed as the first argument.
For example:
example.on("all", function(eventName) {
object.trigger (eventName);
});
Parameter Values:
- event: It is used to bind an object with an event.
- callback: It is executed when an event is invoked.
- context: It is an object which is passed to a callback function.
Example 1: This example describes the Backbone.js on Event.
HTML
<!DOCTYPE html>
< head >
< title >Backbone.js On Event</ title >
< script src =
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
</ head >
< body >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< h3 >Backbone.js On event</ h3 >
< script type = "text/javascript" >
var obj = {};
_.extend(obj, Backbone.Events);
var counter = 0;
obj.on('trigger', function() {
counter++;
document.write(
'< h2 style = "color:blue;" >OUTPUT AFTER TRIGGERING ON EVENT :</ h2 >');
document.write(counter);
alert("triggered");
});
obj.trigger('trigger');
obj.trigger('trigger');
</ script >
</ body >
</ html >
|
Output:
Example 2: This example describes Backbone.js on Event specifying the multiple events.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Backbone.js on event</ title >
< script src =
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
</ head >
< body >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< h3 >Backbone.js On event</ h3 >
< script type = "text/javascript" >
var value = _.extend({
name: 'GeeksforGeeks'
}, Backbone.Events);
value.on('first', function() {
document.write("Trigger-1) The triggered value is: ");
document.write(this.name);
});
value.on('second', function() {
document.write("< br >");
document.write("Trigger-2) The triggered value is: ");
document.write(this.name);
});
value.trigger('first');
value.trigger('second');
</ script >
</ body >
</ html >
|
Output:
Reference Link: https://backbonejs.org/#Events-on
Share your thoughts in the comments
Please Login to comment...