Jquery click event calling parent class method

Hi how do access the update function of my class method within jquery event?

Test.prototype = {

        init: function( ) {
            $("#myBtn").click(function( ) {
                this.update(); // "this" doesn't work
            });
        },

        update: function( val ) {
            alert("called")
        }
}

Appreciate anyone who can shed some light here.

From the jquery docs.

The handler parameter takes a callback function, as shown above. Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function.

One was you can do it is just save the value of this outside the callback function and reference that.


init: function( ) {
  var that = this;
  $("#myBtn").click(function( ) {
    that.update();
  });
}

Coffeescript makes it easier with the fat arrow => for binding the value of this to functions.


init: ->
  $("#myBtn").click =>
    this.update()