Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Backbone.js listenTo Event notifies an object to listen to a particular event on another object. The benefit of using this form is that listenTo permits the object to keep the track of the events, and later, even they are removed all at once. When an event occurs, the callback function will be called with the object as context.
Syntax:
Object.listenTo( other , event, callback);
Parameter Values:
- other: This parameter is used to define the name of the object.
- event: This parameter is used to bind the event with an object.
- callback: This parameter is used to make reference to the function which is called when an object bind event occurs.
Example 1: This example describe the Event listenTo() function in BackboneJS.
HTML
<!DOCTYPE html> < html > < head > < title > BackboneJS listenTo 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;" > neveropen </ h1 > < h3 >BackboneJS listenTo Event</ h3 > < script type = "text/javascript" > var first = _.extend({ value: 'neveropen ', }, Backbone.Events); var second = _.extend({ value: 'Backbone Event listenTo', }, Backbone.Events); let callback = function() { document.write(`</ br >This is ` + this.value + ` course.`); }; first.listenTo(first, 'listenVar', callback); second.listenTo(second, 'listenVar', callback); first.trigger('listenVar'); </ script > </ body > </ html > |
Here, the _.extend() function is used to create a copy of all the properties of the source objects over the destination object and return the destination object.
Output:
Example 2: This example describes when we are listening to an object until the page is destroyed if we bind the event with the object. The Backbone.js listenTo always whenever bind event trigger.
HTML
<!DOCTYPE html> < html > < head > < title > BackboneJS listenTo Event Multiple times </ 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;" > neveropen </ h1 > < h3 > BackboneJS listenTo Event </ h3 > < script type = "text/javascript" > var temp = _.extend({ value: 'Backbone Event listenTo', }, Backbone.Events); let callback = function() { document.write(`</ br >This is ` + this.value + " "); }; temp.listenTo(temp, 'event', callback); for(let i = 1; i < 6 ; i++) { temp.trigger('event'); document.write(i + " time"); } </script> </ body > </ html > |
Output:
Reference: https://backbonejs.org/#Events-listenTo