2012-07-30 42 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