November 26, 2016

Backbone JS Event ON example

ON Event

Syntax: object.on(event, callback, [context])
It will bind a callback function to an object. The callback will be invoked whenever the event is fired or triggered. We can bind single or multiple events in the same object to get it triggered.

Example with single event:


 <!DOCTYPE html>  
   <head>  
    <title>Event On Example</title>  
      <script src="jquery-3.1.1.min.js" type="text/javascript"></script>  
      <script src="underscore-min.js" type="text/javascript"></script>  
      <script src="backbone-min.js" type="text/javascript"></script>  
   </head>  
   <body>  
    <script type="text/javascript">  
         //Here creating an object 'myVal' and extending with Backbone.Events method  
      var myVal = _.extend({name:'Hello World'}, Backbone.Events);  
      // The on() method will bind callback function to an object and invoked whenever an event triggers  
      myVal.on('myFunc', function () {  
       alert(this.name);  
      });  
      //It triggers the 'myFunc' event on object 'myVal'  
      myVal.trigger('myFunc');  
    </script>  
   </body>  
 </html>  

Example with multiple event:

 <!DOCTYPE html>  
   <head>  
    <title>Event On Example</title>  
      <script src="jquery-3.1.1.min.js" type="text/javascript"></script>  
      <script src="underscore-min.js" type="text/javascript"></script>  
      <script src="backbone-min.js" type="text/javascript"></script>  
   </head>  
   <body>  
    <script type="text/javascript">  
      //Here creating an object 'myVal' and extending with Backbone.Events method  
      var myVal = _.extend({name:'Hello World'}, Backbone.Events);  
      // The on() method will bind callback function to an object and invoked whenever an event triggers  
      myVal.on('change hide', function (message) {  
       alert(this.name + message);  
      });  
      //It triggers the 'change' event on object 'myVal'  
      myVal.trigger('change', ' with change trigger');  
      //triggers the 'hide' event on object 'myVal'  
      myVal.trigger('hide', ' with hide trigger');  
    </script>              
   </body>  
 </html>  

No comments:

Post a Comment