Which method tells an object to listen to the particular event on another object which provides call back function when an event occurs and also keeps track of events. The syntax below demonstrates the Event listen To.
[code]
object.listenTo(other, event, callback)
[/code]
Parameters
- other
Which is used to define the name of the other project.
- event
it is used to bind an object.
- callback
Which reference to the code and called with the object as context.
The code below demonstrates the Event listenTo() as shown below.
[html]
<!DOCTYPE html>
<head>
<title>Event listenTo Example</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
//Create an object 'myVal' and 'myVal1' and extend them using Backbone.Events method
var myVal = _.extend({name:'Hello..'}, Backbone.Events);
var myVal1 = _.extend({name:'Welcome to splessons'}, Backbone.Events);
//create the 'listenMe' callback function and invoke when one object listens to particular event on another object
var listenMe = function(){
document.write("The value is: ");
document.write(this.name);
};
//The object 'myVal1' listens once for the 'listenMe' event triggered on object 'myVal'
myVal1.listenTo(myVal, 'listenMe', listenMe);
//The 'myVal' has no listenMe event and displays the value of 'myVal1'
myVal.trigger('listenMe');
</script>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser user can get the following output as shown in below image.