AlexCheuk
AlexCheuk

Reputation: 5845

How do get class variable within an event handler with "this"

Here is some code:

var class = function(elem,div){

    this.elem= elem;
    this.div = div;

    this.init = function(){
        this.div.bind('keyup',this.handler);
    }

    this.handler= function(event){
        //HOW DO I GET "this.elem" ???
        //here, this = div
    }

    this.init();
}

I want to get the variable "elem" from within my "handler" function, but everytime i call this.elem, the "this" is referring to the elem that was bound to the event handler!!.

Upvotes: 1

Views: 655

Answers (4)

RobG
RobG

Reputation: 147363

elem is captured in a closure, simply reference it as elem:

this.handler= function (event) {
     //HOW DO I GET "this.elem" ???
     //here,

     elem; // elem from the constructor.

     this = div
} 

Also

  1. there are no classes in javascript.

  2. class is a reserved word and you should not use it for an identifier name.

  3. I guess from your names and the way you used them that elem is a DOM element and div is a DIV element. If so, they don't have a bind method. If you want to assign a listener, then:

    this.onkeyup = this.handler;
    

but that must be placed after you define this.handler.

Upvotes: 0

hvgotcodes
hvgotcodes

Reputation: 120178

I suspect you are registering this.handler as the event handler itself. In this case, the method is not being executed in the context of the object; it's being executed like any other event handler.

Try writing a simple handler that invokes your handler method on an instance of class.

var instance = new class(...); // populate args that make sense 
document.yourElement.onclick = function(){
   instance.handler();
}

Also, you really should use prototype to define instance methods. Doing it the way you are doing it is very inefficient.

var class = function(elem,div){

    this.elem= elem;
    this.div = div;

    this.init();
}


class.prototype.init = function(){
        this.div.bind('keyup',this.handler);
    }

class.prototype.handler= function(event){
        //HOW DO I GET "this.elem" ???
        //here, this = div
    }

Upvotes: 1

jAndy
jAndy

Reputation: 235962

If you're cool in using ES5, you might want to invoke the Function.prototype.bind method. Like

this.handler= function(event){
    //HOW DO I GET "this.elem" ???
    //here, this = div
}.bind(this)

There are also lots of shims for that method available to gracefully support old'ish browsers. The above code would cause that the function which is stored in this.handler gets bound to the value of this when the method is called like new class(); forever.

Upvotes: 1

bhamlin
bhamlin

Reputation: 5187

Well, you could just reference elem.

Or you could declare var that = this; outside of the the handler and then reference that.elem.

Upvotes: 1

Related Questions