Nathan Jones
Nathan Jones

Reputation: 5144

How to access other object functions in an event handler function?

I have an object that stores various functions, and one of those functions defines an event callback function. Within this callback function, suppose I want to call other functions that are part of this object. Normally, outside of a callback function, the this variable refers to the object of functions, but in a callback function, this refers to the element that triggered the event.

A simple example:

var objOfFuncs = {
  func1: function() {
    jQelem.on('click', func2);
  },
  func2: function() {
    this.usefulFunc(); // Doesn't work because this no longer referrs to objOfFuncs
  },
  usefulFunc: function(useful) {
    //do useful things
  }
}

My question phrased within the context of the simple example above:

How can I access objOfFuncs within func2, when this refers to whatever triggered the click event?

Upvotes: 0

Views: 40

Answers (1)

adeneo
adeneo

Reputation: 318192

You can pass it as event.data to the event handler, that way you don't loose the scope like you would with apply, call or bind

var objOfFuncs = {
  func1: function() {
      jQelem.on('click', {obj: this}, this.func2);
  },
  func2: function(e) {
    e.data.obj.usefulFunc();
  },
  usefulFunc: function(useful) {
    console.log('works')
  }
}

FIDDLE

Upvotes: 1

Related Questions