Mootools Element.prototype错误

时间:2012-07-30 19:16:38

标签: javascript mootools

我想在mootools的Element成员中实现一些函数和变量。我有类似的东西

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

之后我创建一个新元素并将mousewheel事件绑定到span并访问它的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();
            }
        }
    });

问题是我收到以下错误:

  

未捕获的TypeError:对象[对象窗口]没有方法'getFirst'

你知道这会导致什么吗?

LE:是的,我期待'this'成为一个元素。但我不明白为什么它会是Window类型。

2 个答案:

答案 0 :(得分:1)

使用Implement来更改原型。你需要一个函数,不能说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();
}

答案 1 :(得分:0)

感谢您的快速解答。同时我找到了一种基于Dimitar第一解决方案的方法。它看起来像这样:

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