Background: I am building a webapp that makes use of JQuery and the Facebook Javascript API. Since some users don’t like Facebook, I have also built a thunking layer that emulates the necessary identity APIs for users who prefer not to use Facebook. To keep things clean and avoid code duplication, I have organized my Javascript code into a few classes.
Both Facebook and JQuery APIs make extensive use of callbacks. Since all of my functions are bound into objects, I found that I am using the following pattern frequently:
var obj_ref = this;
some_jquery_function_that_takes_a_callback(/* various args */,
function() { obj_ref.my_callback_method(); });
For readability, the obj in obj_ref is actually the name of the class.
Is there some nifty Javascript magic that is simpler or clearer, or is this as good as it gets?
Update: Some good commentary so far in the answers. I should have added that my callback methods generally needs to refer to variables or functions bound to the class. If I don’t need that, then the anonymous function wrapper is unnecessary.
Update2: I’ve selected a best answer, but you should carefully read all of the answers. Each provides some useful insight into possible solutions.
If you need your
thisto be yourobj_refand you can assume an update to date JavaScript (which sadly you probably can’t), you could usebindto do away with the wrappers:Then you could bind your methods to your objects and this:
would be the same as:
Then
thiswould beobj_refwhenmy_callback_methodis called.Alternatively, you could pull in Underscore.js and use its
bindorbindAll. You could always grab justbindorbindAllout of Underscore.js if you didn’t want the whole thing.Or, since you have jQuery in play already, you could use
$.proxyin place of the standardbind:So you could do it like this:
Thanks to dsfq for reminding me about jQuery’s version of
bind.