Binding Methods to Objects
by Geethalakshmi[ Edit ] 2010-09-16 21:21:01
Binding Methods to Objects
Anyone who works with JavaScript events may have come across a situation in which they need to assign an object's method to an event handler. The problem here is that event handlers are called in the context of their HTML element, even if they were originally bound to another object. To overcome this, I use a function that binds a method to an object; it takes an object and method, and returns a function that always calls the method in the context of that object. I found the trick in Prototype, and wrote the following function to use it in projects that don't include Prototype:
function bind(obj, method) {
return function() { return method.apply(obj, arguments); }
}
And this snippet shows how to use the function:
var obj = {
msg: 'Name is',
buildMessage: function (name) {
return this.msg + ' ' + name;
}
}
alert(obj.buildMessage('John')); // displays: Name is John
f = obj.buildMessage;
alert(f('Smith')); // displays: undefined Smith
g = bind(obj, obj.buildMessage);
alert(g('Smith')); // displays: Name is Smith