SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2007
    Posts
    170
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    jquery click event calling parent class method

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

    PHP Code:
    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.
    I Dunno LOL \(_o)/

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,117
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    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.
    Code javascript:
    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.
    Code coffeescript:
    init: ->
      $("#myBtn").click =>
        this.update()


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •