2010-09-15 80 views
1

由於在發送element.addEvent中的方法時我無法使用「this」,因此在實現mootools中的類時出現問題。如何在mootools類中的函數中調用此函數

說我有這樣的mootools類:

var Dude = new Class({ 

    highlightColor: '#f00', 

    doStuff: function() { 
     var parent = $('theParentId'); 

     new Element('div', {'html': 'Click me'}) 
      .inject(parent) 
      .addEvent('click', function(){ 

       new Element('div', {'html': 'you clicked'}) 
        .highlight(this.highlightColor); 

      }); 
    }, 

}); 

此代碼將拋出的addEvent方法調用內部異常,因爲this突然在另一種情況下。有沒有其他方法來獲取對象的highlightColor(或mootools類可能有的其他成員)?

回答

2

的「MooTools的方式」將使用bindWithEvent功能:

var Dude = new Class({ 

    highlightColor: '#f00', 

    doStuff: function() { 
     var parent = $('theParentId'); 

     new Element('div', {'html': 'Click me'}) 
      .inject(parent) 
      .addEvent('click', function(event){ 

       new Element('div', {'html': 'you clicked'}) 
        .highlight(this.highlightColor); // <- `this` refers to the 
      }.bindWithEvent(this));     // outer `this` value 
    }, 
    //... 
}); 

這種方法可以讓您保存在一個函數this值,並在必要時通過額外的參數。

綁定函數的第一個參數將引用觸發事件的Event對象。

+1

應該使用'bind'來代替'bindWithEvent' - 這是核心開發者鼓勵不要使用'bindWithEvent'的「mootools方式」。 – 2010-09-15 20:40:14

+2

@Oskar,好吧,'bindWithEvent'已經被完全做成了,[documentation](http://j.mp/cAoTn4)在使用addEvent時特別推薦它的用法:「這允許函數與Element一起使用:addEvent和arguments。「,儘管我承認使用bind的好處之一是,ECMAScript 5標準的本地實現Function.prototype.bind將很快在所有瀏覽器上提供,本機實現總是有很好的性能。無論如何,如果Core開發人員不鼓勵使用此方法,那麼文檔中的註釋將會有所幫助。 – CMS 2010-09-15 20:49:10

+0

我同意Oskar的意見,它使用'bind'更常見 - 保持範圍到類實例的工作就像這樣完成。就我的理解而言,在這裏你不需要'bindWithEvent' - 他在回調中訪問的所有內容都是'this.highlightColor'屬性,所以將範圍保持到類實例就足夠了。該事件根本不需要傳遞,因爲回調已經按照定義直接訪問它。例如'... click ...「,this.methodName.bind(this)'也會將事件對象傳遞給方法作爲第一個參數,那麼'bindWithEvent'有什麼好的測試用例嗎? – 2010-09-16 00:18:53

3

你需要每次使用的功能(上addEventseach)時間

var Dude = new Class({ 

    highlightColor: '#f00', 

    doStuff: function() { 
     var parent = $('theParentId'); 

     new Element('div', {'html': 'Click me'}) 
      .inject(parent) 
      .addEvent('click', function(){ 

       new Element('div', {'html': 'you clicked'}) 
        .highlight(this.highlightColor); 

      }.bind(this)); 
    } 
}); 

是carefoul與功能doStuff最後昏迷參考功能綁定... Firefox是像一個母親會foregive你,但IEXPLORER是BMF將拋出一個錯誤,並不會告訴你爲什麼

2

@CMS是在一個正確的軌道,但bindWithEvent現在已經過時和documentation建議使用此代碼來代替:

myElement.addEvent('click', function(e){ 
    myFunction.call(bind, e); 
}); 


如果你想將事件綁定元素傳遞給你的類方法,你可以做這樣的:

var self = this; // 'this' is class reference 
elements.addEvent('click', function(e){ 
    self.myClassMethod(this, e); // now 'this' is clicked element 
}); 

現在你得到了正確的元素傳遞給你的方法,並準備操縱上。