Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Event handling in jQuery widgets

Posted by Dave Mahon

This is simple – provided you understand that the reference the keyword this refers to changes depending on when it is called.

When called during initialization, this refers to the widget you’re initializing. When the event itself is triggered, this refers to the DOM node node and not the widget.

As such, we need to introduce a new variable during initialization which the jQuery.UI library calls self which is, of course, equal to the initialization this, not triggered this. (Those of you familiar with Object Oriented Programming and by-reference calls should have no issue with this concept).

<$.widget("ui.clicker", {
   _init: function() {
      self = this;
      this.element.click(function() {
         self.increment(self);
         self.render();
      });
      this.render();
   },
   increment: function(target) {
      target.value(target.value()-1);
      //The exact handling of target.value will be shown another day
   },
   render: function() {
      this.element.text(this.value());
   },
   value: function(val) {}
});

You’ll note that we have to pass self to the increment method or the widget won’t actually be able to find itself, but the render method, which was called during initialization, is henceforth always able to correctly reference this (the widget)!

  • No Related Post

Comments are closed.