开发者

Passing Class Variables to Class Method in Prototype via addEventListener

I have the following class file that I'm attempting to build. I'd like to pass multiple variables to the method by way of an eventListener but the code I have below doesn't work, probably due to scoping. NOt sure what I should change though. Any advice would be much appreciated.

var MyClass= new Class.create();
MyClass.prototype = {
    initialize: function(id,name,top,left){
        try开发者_Python百科{
            this.id = id;
            this.name = name;
            this.currentTop = top;
            this.currentLeft = left;

            $(id).addEventListener("mousedown",function(event,this.id,this.name){
                this.grabOBJ(event,this.id,this.name);
            },false);

        }
        catch(error){alert(error);}
    },
    grabOBJ:function(event,myID,myName){
        // do something here with myID and myName
    }
};


Your syntax is completely wrong.

Instead, you should make a separate variable to hold the real this, like this:

var MyClass= new Class.create();
MyClass.prototype = {
    initialize: function(id,name,top,left){
        try{
            this.id = id;
            this.name = name;
            this.currentTop = top;
            this.currentLeft = left;

            var self = this;

            $(id).addEventListener("mousedown",function(event){
                self.grabOBJ(event);
            }, false);

        }
        catch(error){alert(error);}
    },
    grabOBJ:function(event){
        // do something here with this.id and this.name
    }
};

Since self.grabOBJ is a normal method call, its this will be the MyClass instance.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜