Extracting Prototype’s Bind()
Of the current JS frameworks, I’m most familiar with Prototype.js. This is purely because it was the first one I tried out and is not due to a real preference.
I prototyped a current project using Prototype.js but have since learned that the client wishes to use jQuery as their base library. My work doesn’t extensively exploit Prototype.js (I tried to write as much agnostic code as possible) so I figured it’d be easy to port it to jQuery… and in the most part it has been!
However, jQuery doesn’t (so far as I can see) have the facility to pass the scope of a callback function, implicitly or otherwise. This is what Prototype.js’s “bind()” extension does: it binds the function to a given object.
var obj = {
name : 'Richard'
}
var sayName = function(){
alert(this.name);
}
var eg = sayName.bind(obj);
eg();
This example would alert “Richard”, because when sayName() is executed it’s bound to obj: it’s like calling obj.sayName();. This is REALLY useful when using callback functions - in my opinion it’s a necessary extension, otherwise you either scrap handling the callback scope or have to deal with passing two parameters (function, scope) for every callback.
So, as it’s something I can’t live without and because the client wants jQuery, I’ve extracted Prototype.js’s bind() extension into bind.js:-
/**
* The "bind()" function extension from Prototype.js, extracted for general use
*
* @author Richard Harrison, http://www.pluggable.co.uk
* @author Sam Stephenson (Modified from Prototype Javascript framework)
* @license MIT-style license @see http://www.prototypejs.org/
*/
Function.prototype.bind = function(){
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions:arguments
var _$A = function(a){return Array.prototype.slice.call(a);}
if(arguments.length < 2 && (typeof arguments[0] == “undefined”)) return this;
var __method = this, args = _$A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat(_$A(arguments)));
}
}
This will now complement jQuery and allow me to continue using .bind() when passing functions around.
Tags: code, javascript, jquery, prototype
October 5th, 2008 at 2:44 pm
Thanks - this was very helpful to me as well. I’m using YUI.
March 25th, 2009 at 10:30 pm
Hey, thanks a ton for this — it was exactly what I needed. Stupid of me not to think of just going into Prototype and grabbing it for myself.