jQuery: binding objects to events

Each jQuery event has a data object attached to it. This object can store any kind of data, including simple object properties or even object methods. You can define a separate object and then associate it with your event through data. This object is the second parameter of the bind() method used to attach an event to a page element. Once you associate your custom object with data, you can later reference your object methods and properties using data. An example:

var Class = {

  property: 'Test',
  get: function() {
  
    alert(this.property);
  
  }

};

This is a simple object that we're going to associate with data. The syntax of bind() is as follows:

element.bind(eventType, data, handler)

So we need to use our object name as the second parameter of bind():

$('#test').bind('click', Class, function(event) {

  ...

});

Doing this, we've associated Class with data. Now we can call our object method as follows:

$('#test').bind('click', Class, function(event) {

  event.data.get();


});

You can see this example below.

Example

Live example

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.