BackboneJS - Event On


Advertisements

Description

It binds an event to an object and the callback function. Whenever an event is fired, it executes the callback.

Syntax

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

Parameters

  • event − It binds an object.

  • callback − It is the reference to the code.

  • context − It is an object that can be passed to a callback function.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Event On 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">
         //Here creating an object 'myVal' and extending with Backbone.Events method
         var myVal = _.extend({name:'TutorialsPoint!!!'}, Backbone.Events);
         
         // The on() method will bind callback function to an object and 
         // invoked whenever an event triggers
         myVal.on('myFunc', function () {
            document.write("The triggered value is: ");
            document.write(this.name);//The name will get display by referring the current object
         });
         
         //It triggers the 'myFunc' event on object 'myVal'
         myVal.trigger('myFunc');
      </script>
      
   </body>
</html>

Output

Let us carry out the following steps to see how the above code works −

  • Save above code in on.htm file

  • Open this HTML file in a browser.

backbonejs_events.htm
Advertisements