5

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?

2 Answers 2

6

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).

Sign up to request clarification or add additional context in comments.

Comments

4

Jquery has a method for that, jQuery.proxy( function, context ):

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(
      $.proxy(function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      },this)
    )
  }
}

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.