Tutorial :JQuery Widget Events in Object Orientated Javascript



Question:

I'm attempting to write a custom widget and I want to use existing UI widgets within the class that I'm writing. The problem is that when an event fires the class method that is invoked seems out of scope from the rest of the class, as any members I attempt to read are undefined. Here is the code:

<script type="text/javascript">  MyClass = function()  {      this.init();  }    $.extend(MyClass.prototype,       {             init: function()          {              this.field = 'Hello world.';                /* Let's try using a slider. */              this.slider = $("#slider");                this.slider.slider(                  {                      change: this.callback,                      min: 270,                      max: 800,                      slide: this.callback                  }              );          },            callback: function()          {              alert(this.field);          }      }  );  </script>    <div id="slider"></div>  <script type="text/javascript">  var myClass = new MyClass();  </script>  

This is a simplification of the problem, and I have tried a few methods to get around this, such as using bind instead of the callback notation:

this.slider.bind('slidechange', this.callback(this));  this.slider.bind('slide', this.callback(this));  

However, this just leads to the call back being invoked despite the event occuring.

Thanks.


Solution:1

See http://www.alistapart.com/articles/getoutbindingsituations/ for methods on binding this, using closures

EDIT: As a concrete example of how this can be achieved...

$.extend(MyClass.prototype,   {         init: function()      {          this.field = 'Hello world.';            /* Let's try using a slider. */          this.slider = $("#slider");            this.slider.slider(              {                  change: this.callback(this),                  min: 270,                  max: 800,                  slide: this.callback(this)              }          );      },        callback: function(that)      {          return function() {              alert(that.field);          }      }  }  );  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »