Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to object property inside jQuery event function

Sorry for my english. Here is example code:

/**
 * @constructor
 */
function MyNewClass(){
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      }
    )
  }
}

How can i access objects my_value property inside jQuery click event function? Is it possible?

like image 742
MaratMS Avatar asked Sep 25 '13 12:09

MaratMS


1 Answers

You can do the following

function MyNewClass(){
    this.$my_new_button = $('<button>Button</button>');
    this.my_value = 5;
    var self = this; //add in a reference to this
    this.init = function (){
        $('body').append(this.$my_new_button);
        this.$my_new_button.click(
            function (){
                //This will now alert 5.
                alert(self.my_value);
            }
        );
    };
}

This is a small pattern in javascript (although the name eludes me). It allows you to access top level members of a function within an inner function. In a nested function you can't use "this" to refer to top level members as it will only refer to the function you are within. hence the need to declare the top level functions "this" value into its own variable (called self in this case).

like image 123
BenM Avatar answered Oct 15 '22 09:10

BenM