开发者

Mootools -- call class function from bound css class results in 'not a function' error

Using Mootools 1.3.2

Code is as follows:

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;
}
});

The event does bind, and when "this.reportComment();" is replaced with "alert('hello world');" it works entirely ...

... but when "this.reportComment()" is used, I instead receive an error, which Firebug explains as "function this.reportComment() is not a function".

I imagine that my issue has something to do with referring to a class function outside of its proper scope, though I'm a bit confused as to why ... or how to solve the issue. The end goal is to achieve an on-click binding of the reportComment() function to all members of a css class (up to 20 per page). The difficulty is that referencing the reportComment() function with "this.开发者_开发知识库reportComment()" results in an error claiming that the function does not exist, when it clearly does exist.

Looking through similar questions on Stack Overflow did not seem to answer this issue ... so asking in hopes that someone can point me in the right direction.


You have some problems with bind and events:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜