Seeing so many JQuery fans out there, I’d like to share a little trick I use when I run JQuery alongside the MS AJAX Library.
There’s one very confusing aspect of JavaScript: the this keyword. What does this point to at any given time? The answer is it depends. It’s often difficult to figure it out. Just about the best and most detailed explanation of JavaScript closures, execution contexts, scope chains, the this keyword, etc, is here: JavaScript Closures.
When you write a new client-side component—a behavior or a client control—you declare a “constructor” and then augment the “class” prototype:
MyNamespace.MyControl = function (element) {
MyNamespace.MyControl.initializeBase (this, [element]);
// ...
this._addPanel = null
}
MyNamespace.MyControl.prototype = {
initialize: function () {
MyNamespace.MyControl.callBaseMethod (this, 'initialize');
var self = this;
var el = self.get_element();
// ...
var addLink = document.createElement ('a');
$(addLink).click (function (evt) {
$(self._addPanel).show ();
evt.preventDefault ();
});
// ...
}
}
I simply save this because I know it’ll change hands inside various closures. It’s easy enough to forget you’re inside a closure when writing a mad “jquery” so this doesn’t point to your component anymore.
In the sample above I have a hyperlink whose click handler should display an arbitrary panel. I store this panel DOM element in a “private” field of my component. I can’t write $(this._addPanel).show() because
this will point to the hyperlink when the click handler is invoked. Saving this in variable self allows me to get to the panel.
This simple technique has saved me a lot of debugging time. Hope it helps someone.