Sanal.org
till 01th May 2006
Categories
.NET (40)
Art (1)
Blogs (1)
Computers (6)
Information (13)
Internet (11)
Movies (5)
Music (19)
MY SQL (5)
People (16)
Russian (20)
Security (15)
SEO (3)
SQL SERVER (8)
Technology (6)
Turkey (2)
Video (7)
More
TOP 50
Turkish News


Archive
April (2008)
March (2008)
February (2008)
January (2008)
December (2007)
Novamber (2007)
October (2007)
September (2007)
August (2007)
July (2007)
June (2007)
May (2007)
April (2007)
March (2007)
February (2007)
January (2007)
December (2006)
Novamber (2006)
October (2006)
September (2006)
August (2006)
July (2006)
June (2006)
May (2006)
April (2006)
March (2006)
February (2006)
January (2006)
December (2005)
October (2005)
April (2005)
December (1969)

96

ROR

MS AJAX Library and JQuery: What Does 'this' Point To?


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.




0.015625
Bilgi Portalı | Forum | Haberler | Havacılık | Daily News | Noticias