Load WordPress Sites in as fast as 37ms!

Javascript callbacks and the “this” object.

I spent hours and hours googling for this and the word “this” being a very common word made it impossible to find the answer.

The question was; how do I use the “this” context-object in my own callback function. It turns out it’s very simple, but the trick is, of course, to know the answer to know it’s simple.

Imagine the following situation;

You have a function you want executed (a callback, a closure) and you want to do that from inside another closure (because there’s more logic involved).

The callback containing it all is called by an event binder, say, onkeydown, and you need the context object inside the other callback.

O.k., this is getting hard to explain, let me show you; this is what I did;

Reason? on enter, move to next field, add a new row of inputs, make the background flash, whatever.

html<input type="text" id="the_input" value="some text" />
javascript/jQuery(function($){
$.fn.redirectEnter = function(callback) {
return $(this).bind('keydown', function(e) {
if (e.keyCode == 13) {
callback();
return false;
}
});
};
})(jQuery);
jQuery("#the_input").redirectEnter(function() {
alert('you pressed enter!');
});

But now, I want to know what input the enter key was pressed, which is easy in the jQuery plugin; it’s “this”, but I need that “this” object in my closure; I want to use the object there. Not knowing how and not being able to find it, I just passed along “this” as a parameter. Also, I added the event object, just in case.

javascript/jQuery(function($){
$.fn.redirectEnter = function(callback) {
return $(this).bind('keydown', function(e) {
if (e.keyCode == 13) {
callback(this, e);
return false;
}
});
};
})(jQuery);
jQuery("#the_input").redirectEnter(function(object, event) {
alert('you pressed enter after typing '+ jQuery(object).val() +'!' );
});

It works, but it’s not intuitive. This having the purpose of a recyclable plugin, it should handle as all other plugins and callbacks etc.

It took me a while to find out (and I had to dig into jQuery’s uncompressed code to find it) that a callback can be applied to an object. Go figure;

javascript/jQuery(function($){
$.fn.redirectEnter = function(callback) {
return $(this).bind('keydown', function(e) {
if (e.keyCode == 13) {
callback.apply(this, e);
return false;
}
});
};
})(jQuery);
jQuery("#the_input").redirectEnter(function(event) {
alert('you pressed enter after typing '+ jQuery(this).val() +'!' );
});

And all the world makes sense again :)

Hope this helps you. Thank you for reading, and if you want to use this plugin, be my guest – leave me a comment :)

Author: Remon Pel

WebDeveloper though not WebDesigner

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.