2012-07-30 17 views
1

我想將一些函數和變量實現到mootools的Element成員中。我有這樣的事情Mootools Element.prototype error

Element.prototype.currentChild = this.getFirst(); 
Element.prototype.scrollToNext = function(delta, tag){ .... } 

後,我創建一個新的元素和鼠標滾輪事件綁定到跨度和存取權限是currentChild。

body_container = new Element('div', { 
events:{ 
      'mousewheel': function(e){ 
       var elem = new Element(this); 
       elem.currentChild.setStyle('background-color', 'transparent'); 
       elem.scrollToNext(e.wheel); 
       elem.currentChild.setStyle('background-color', '#C6E2FF'); 
       e.stop(); 
      } 
     } 
    }); 

的問題是,我得到以下錯誤:

Uncaught TypeError: Object [object Window] has no method 'getFirst'

你知道什麼可能會導致這樣? LE:是的,我期待'this'是一個元素。但我不明白爲什麼它會是Window類型。

+0

你有什麼期待'this'是在這裏:*'Element.prototype.currentChild = this.getFirst();'* – Esailija 2012-07-30 19:18:16

+0

嗯,這顯然是一個'Window'對象而不是預期的「元素」。 – TheZ 2012-07-30 19:18:22

回答

1

使用實現來改變原型。並且你將需要一個函數,不能說something.prototype.method = this.somethingsMethod,因爲它不在方法的執行上下文之外。

Element.implement({ 
    currentChild: function() { 
     return this.getFirst(); 
    }, 
    scrollToNext: function() {} 
}); 

MooTools也有別名。

Element.alias('currentChild', 'getFirst'); 

https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L223-225 - 走樣的類型的方法,當你不想重新實現。

說實話,爲什麼你不能只用元素存儲呢?

'mousewheel': function(e) { 
    var elem = document.id(this), 
     first = elem.retrieve('currentChild'); 

    first || elem.store('currentChild', first = elem.getFirst()); 

    first.setStyle('background-color', 'transparent'); 
    elem.scrollToNext(e.wheel); 
    first.setStyle('background-color', '#C6E2FF'); 
    e.stop(); 
} 
+0

但它會是靜態的? – 2012-07-31 06:31:00

+0

我用這種方法,但我想currentChild實際上是一個變量而不是一個函數。聲明currentChild:this.getFirst();只是一個初始化。之後,它會更新。 – user1552480 2012-07-31 06:44:44

+0

它不是靜態的。 – user1552480 2012-07-31 07:08:21

0

感謝您的快速回答。同時我發現了一個基於Dimitar第一個解決方案的實現方法。它看起來像這樣:

Element.implement({ 
    currentChild: function(){ 
     if(!this._currentChild) this._currentChild = this.getFirst(); 
     return this._currentChild; 
    } 
} 
+0

這比'.store' /'.retrieve'慢,特別是在IE中。 – 2012-07-31 16:05:50