by Jim
Jan 29, 2011 8:38 PM
My current project requires me to make a lot of asynchronous calls with javascript, and even to chain these calls. After a lot of refactoring I’m comfortable with the way I’m handling this, but I spent a while fighting with context and having the ‘this’ keyword point to something different every time I used it.
I’m using jQuery for this project. Part of my solution is to explicitly switch context at certain times; the means of doing this is not immediately obvious, I think, from the jQuery documentation, but it’s simple enough.
Given a context object with a function pointer, some data to pass as an argument, and an object whose context I want to switch to (i.e., that object will be the ‘this’ in the invoked function,) I do this:
var p = $.proxy(context.method, context.reader);
p(context.data);