moteutsch
moteutsch

Reputation: 3831

Event Handler Called With Wrong Context

In the SomeObj object, the onkeydown event handler this.doSomething is called in the wrong context (that of the textbox element) but it needs to be called in the context of this. How can this be done?

function SomeObj(elem1, elem2) {
    this.textboxElem = elem1;
    this.someElem = elem2;
    this.registerEvent();
}

SomeObj.prototype = {
    registerEvent: function() {
        this.textboxElem.onkeydown = this.doSomething;
    },
    doSomething: function() {
        // this must not be textboxElem
        alert(this);
        this.someElem.innerHTML = "123";
    }
};

Upvotes: 0

Views: 382

Answers (1)

Guffa
Guffa

Reputation: 700372

Copy the reference to a local variable, so that you can use it in a closure:

registerEvent: function() {
  var t = this;
  this.textboxElem.onkeydown = function() {
    t.doSomething();
  };
},

Upvotes: 2

Related Questions