views:

73

answers:

1

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{
            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
    }
};
A: 

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.

SLaks
Ah, yes. I see now. I can't believe I missed that. Thanks for the pointer SLaks!
Matt Torbin