2009-06-06 27 views
2

我正在嘗試編寫一個自定義小部件,並且我想在我正在編寫的類中使用現有的UI小部件。問題是,當一個事件觸發時,被調用的類方法似乎超出了該類的其餘部分,因爲我嘗試讀取的任何成員都是未定義的。下面是代碼:面向對象的Javascript中的JQuery小部件事件

<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> 

這是問題簡單化,我已經嘗試了一些方法來解決這個問題,如使用bind,而不是回調符號:

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

然而,這隻會導致回調被調用,儘管事件發生。

謝謝。

回答

3

http://www.alistapart.com/articles/getoutbindingsituations/的方法上結合this,使用閉

編輯: 作爲如何可以做到這一點的具體例子...

$.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); 
     } 
    } 
} 
); 
+0

感謝例如Johathan,這個工程。 Artem,我沒有遵循回調()。apply(this)方法。我需要在哪裏做你的建議? – 2009-06-06 17:11:49