JQuery equivalent of MooTools bind(this)
TBH, the mootools
.bind
as you call it is just Function.bind
in ES5 - and is available natively in browsers that support the js 1.8.5 + spec. MooTools just enhances browsers that don't have it yet but lets the native implementation remain on the prototype - if available.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
You can easily implement that as a a Function.prototype.bind
decorator if not available natively and use it as the example above says:
// Function.prototype.bind polyfill
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
if(typeof this !== 'function') // closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ),
args.concat( slice.call(arguments) ) );
};
bound.prototype = this.prototype;
return bound;
};
}
As you can see, it's a little more involved than a simple .apply
/ .call
One thing to consider is, if you NEED to use bind or if you can save a reference instead.
eg.
var self = this;
this.target.bind("click", function(e) {
var tip = self.opts.tip;
});
this has a smaller footprint than the function binding anyway. it also affords you a correct reference to this
as the trigger element (event.target === this
). you will find this pattern far more often in mootools-core than the bind one - though bind is often needed when you want to assign events to class methods, eg:
this.element.addEvents({
click: this.showTip.bind(this),
mouseleave: this.hideTip.bind(this)
});
In this case, saving a reference won't work though you can rewrite it as
var self = this;
this.element.addEvents({
click: function(e) {
self.showTip(e);
}
});
A jQuery particular implementation is proxy
- http://api.jquery.com/jquery.proxy/