【问题标题】:Mootools -- call class function from bound css class results in 'not a function' errorMootools - 从绑定的 css 类调用类函数导致“不是函数”错误
【发布时间】:2011-07-11 17:18:04
【问题描述】:

使用 Mootools 1.3.2

代码如下:

var DNReportAbuse = new Class({

Extends: DNUserDialog,
comment_id: null,
container: null,

initialize: function(classname) 
{
    var bindclass = $(document.body).getElements(classname);

    bindclass.each(function(el) {
        el.addEvents({
            click: function() {
                this.reportComment();
            }.bind(this)
        });
    });
},

reportComment: function() {
    this.preventDefault();
    alert('hello');
    return false;
}
});

事件确实绑定,并且当“this.reportComment();”替换为“alert('hello world');”它完全有效......

...但是当使用“this.reportComment()”时,我收到一个错误,Firebug 将其解释为“函数 this.reportComment() 不是函数”。

我想我的问题与在其适当范围之外引用类函数有关,尽管我对为什么...或如何解决问题有点困惑。最终目标是实现 reportComment() 函数与 css 类的所有成员的单击绑定(每页最多 20 个)。困难在于使用“this.reportComment()”引用 reportComment() 函数会导致错误,声称该函数不存在,而它显然确实存在。

查看 Stack Overflow 上的类似问题似乎并没有回答这个问题......所以希望有人能指出我正确的方向。

【问题讨论】:

    标签: javascript events binding mootools


    【解决方案1】:

    bindevents 有一些问题:

    initialize: function(classname) 
    {
        var bindclass = $(document.body).getElements(classname);
        var _self = this; //var to store the 'real' this you will use
        bindclass.each(function(el) {
            el.addEvents({
                click: function(event) { //pass the event
                    this.reportComment(event);
                }.bind(_self) //'this' is referring to the inner each function callback
            });
        });
    },
    
    reportComment: function(event) {
        event.preventDefault(); //preventDefault on the event, not on 'this'
        alert('hello');
        return false;
    }
    

    【讨论】:

    • 谢谢——这正是我所需要的。我知道我把我的事件和元素混在了某个地方......
    • 在这种情况下你可以只做bindclass.each(fn(el) { el.addEvents({click: this.reportComment.bind(this)});}, this),如果你将范围保持在each loop 中,则不需要匿名包装器:)
    猜你喜欢
    • 2020-04-04
    • 2012-06-14
    • 2020-06-16
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 2012-10-21
    相关资源
    最近更新 更多