Bind Javascript Objects to jQuery events

If you have ever been looking for a way to quickly bind your Javascript objects to jQuery events, then you have come to the right place.

Many jQuery developers already know that the jQuery library provides a method that allows them to capture events on a DOM element using a callback function. For example:

$('#element').bind(function() {
    alert('hello');
})

This is great but what if you want to use an object to capture the event? This is where BindO comes in.

BindO is a jQuery plugin that makes it possible for you to capture jQuery events with an object. I got this idea after taking with Michael on the jQuery mailing list.

Here's an example of how BindO works:

FormMailer = function() {
    // do something here
}
FormMailer.prototype = new Object;
FormMailer.prototype.submit = function(event) {
    alert('About to submit form');
}

// create a new instance of FormMailer
myform  = new FormMailer();

// now bind the click event to myform.submit
$('#element').bind('click',[myform, 'submit']);

You can also use the jQuery shortcut event names.
For example:
$(…).click([myform, 'submit']);

So now you're probably wondering how do you gain access to the element, right?
Here's an example showing how you can access the element that triggered the event:

MyClass.prototype.hideElement = function(event){
    $(event.target).fadeOut();
}

Please note that the "this" keyword will reference object instance and not the DOM element.

Download BindO
You can download the BindO plugin and example files by clicking here. Note: The example requires the jQuery library.

BindO Quick Reference Guide

$(…).bind('event',[object,'method'])
$(…).bind('event',[object,'method','args'])
$(…).bind('event',data,[object,'method',args])

Object – The object to bind the event to.
Method – The name of the method to be invoked on the object
Args – An extra argument that's added to the event object.


Write a comment

  • Required fields are marked with *.

If you have trouble reading the code, click on the code itself to generate a new random code.
Security Code:
 
xwisdom
Posts: 2
Comment
Re: Leaks
Reply #2 on : Mon May 12, 2008, 22:00:09
Hi Rob,

Thanks for the feedback. The unbinding process of the code is handled by the jQuery API in the same was normal events are handled. So if you unbind an event that was created with BindO, jQuery will take care of the clean process.

Have a look at the plugin source to see how it handles the event calls
Rob Stanford
Posts: 2
Comment
Leaks?
Reply #1 on : Fri May 09, 2008, 05:29:48
Hi,

Great plugin, have wondered why jQuery couldn't do this natively. I have one concern: does the plugin handle the unbinding of objects to prevent memory leaks?

Thanks,
Rob