[英]How to call this in a function in a mootools class
我在mootools中實現類時遇到問題,因為當我在element.addEvent
發送方法時不能使用'this'。
假設我有這個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類可能具有的任何其他成員)嗎?
每次使用函數(在addEvents
或each
)時,都需要將此引用綁定到函數
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));
}
});
注意函數doStuff的最后一個昏迷... firefox就像一個母親,它將原諒您,但是iexplorer是bmf,它將引發錯誤,並且不會告訴您原因
@CMS處於正確的軌道上,但是不建議使用bindWithEvent
並且文檔建議使用以下代碼代替:
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
});
現在,您已將正確的元素傳遞給您的方法並准備進行操作。
“ 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
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.