Reputation: 5988
I try to use the following structure in my app: https://gist.github.com/jonnyreeves/2474026
I try to register some callback inside my constructor. I made an example using jquery, actually it's leaflet maps, but the difference shouldn't matter.
function Person() {
this.name = "abc";
$("#something").onSomeEvent(function() {
this.name = "cde";
});
}
How do I properly reference my object-property name, inside the callback?
Upvotes: 0
Views: 98
Reputation: 111062
Use bind
, which is not supported in older IEs, or jquerys proxy
function Person() {
this.name = "abc";
$("#something").onSomeEvent(function() {
this.name = "cde";
}.bind(this));
}
function Person() {
this.name = "abc";
$("#something").onSomeEvent($.proxy(function() {
this.name = "cde";
},this));
}
Upvotes: 1
Reputation: 71
function Person() {
var self = this;
self.name = "abc";
$("#something").onSomeEvent(function() {
//this is right if you need
self.name = "cde";
});
}
you can use $('#someting') with right this.
if you use bind to solve the problem,in the callback this is wrong.
Upvotes: 2
Reputation: 4211
You can use something like this:
function Person() {
this.name = "abc";
$("#something").onSomeEvent(function() {
this.name = "cde";
}.bind(this));
}
Upvotes: 3