Linda
Linda

Reputation: 439

Call a function from inside on()

I need to call a function from the on() handler. In my example code I must call func1(). I use on() as #myid does not exist on load of the document. Here is the code:

func1: function (e, data) {
  console.log('func1');
  this.func3();
},
func2: function (e, data) {
  $('#myid').on('click', function () {
    this.func1();
  });
}
},

This code does not work. The error is:

Uncaught TypeError: this.func1() is not a function

How do I call a function from inside the on()?

Upvotes: 1

Views: 49

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337646

Assuming that these are properties of an object, your issue is because this within the click handler will refer to the #myId element, not the parent object. To fix this you need to cache the this reference in a variable.

Also note that you state you are using on() because the #myId element doesn't exist on load of the page. If that's the case you need to use the delegated signature for the on() method, which you're currently not doing. Try this:

var obj = {
  func1: function (e, data) {
    console.log('func1');
    this.func3();
  },
  func2: function (e, data) {
    var _this = this; // note this variable...

    $(document).on('click', '#myid', function() {
        _this.func1(); // ...and it's use here
    });
  }
};

Upvotes: 2

31piy
31piy

Reputation: 23859

Uncaught TypeError: this.func1() is not a function

You will encounter this error, because the context of this here is different. It points to context of jQuery's element #myid, instead of the original. To get rid of it, try this:

// ... Code removed for brevity

func2: function (e, data) {
         var self = this;

         $('#myid').on('click', function () {
           self.func1();
         });
       }

// ... Code removed for brevity

Upvotes: 5

Related Questions