
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:
// Form Mailer class
FormMailer = function() {
// do something here
}
FormMailer.prototype = new Object;
FormMailer.prototype.submit = function(event) {
alert('About to submit form');
this.process(); // call the process function
$(event.target).fadeOut(); // fadeout #element
}
FormMailer.prototype.process = function() {
// process data here
}
// 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 *.
Posts: 7
Reply #7 on : Sat February 28, 2009, 05:36:06
Posts: 7
Reply #6 on : Fri October 17, 2008, 11:59:02
Posts: 7
Reply #5 on : Thu October 16, 2008, 11:27:40
Posts: 7
Reply #3 on : Wed August 27, 2008, 17:49:55
Posts: 7
Reply #2 on : Mon May 12, 2008, 22:00:09
Posts: 7
Reply #1 on : Fri May 09, 2008, 05:29:48
Subscribe to Feed by Email
Posts: 7
Reply #9 on : Fri January 15, 2010, 10:05:46