I’m trying to rewrite a Mootools tooltip class in JQuery using this class plugin. When my class is instantiated I’m attaching an event listener to a target link which will fade out the tooltip.
In event callbacks JQuery assigns the keyword “this” to the target of the event, so to keep a reference to the properties of the class I’m using apply() to set “this” to mean the class instance. This is apparently the counterpart in JQuery of Mootools’ handy bind() function.
Unfortunately when I use apply() I lose the callback’s event parameter. For example, in this bit I get an “e is undefined” error on the second line.
this.target.bind('click', function(e){
e.preventDefault();
var tip = this.opts.tip;
tip.fadeOut(500, function(){
tip.bind('click', function(){
showing = false;
})
});
}.apply(this))
Am I missing a trick here? Does anybody know a way around this issue?
TBH, the
mootools.bindas you call it is justFunction.bindin 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.binddecorator if not available natively and use it as the example above says:As you can see, it’s a little more involved than a simple
.apply/.callOne thing to consider is, if you NEED to use bind or if you can save a reference instead.
eg.
this has a smaller footprint than the function binding anyway. it also affords you a correct reference to
thisas 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:In this case, saving a reference won’t work though you can rewrite it as
A jQuery particular implementation is
proxy– http://api.jquery.com/jquery.proxy/