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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With