Reputation: 5989
I defined event 'on' to my object ( newobj )
In the event on I need access to this member that I saved it before.
The issue that I don't get this value in on event. ( doesn't exist )
I thought that I need to add closure I tried to add it but it didn't work.
Could you advise me what is the problem ?
Basic code
create : function() {
var self = this;
var newObj = createNewObj()
newObj.on('selectData', function(evt){
///some code on self
});
With closure option 1
create : function() {
var self = this;
var newObj = createNewObj()
return function(){
newObj.on('selectData', function(evt){
///some code
})};
With closure option 2
create : function() {
var self = this;
var newObj = createNewObj()
newObj.on('selectData', function(evt){
})
return function(){
// some code
};
Upvotes: 0
Views: 71
Reputation: 5052
You can use the bind function. This simple changed the this
inside the function.
Try something like this:
create : function() {
var self = this;
var newObj = createNewObj()
return (function(){
newObj.on('selectData', function(evt){
///some code
}.bind(newObj)
)})();
};
Sometime in the future you will be able to use a lexicaly bound function. See this article :)
Upvotes: 0
Reputation: 12635
Try this:
create : function() {
var self = this;
var newObj = createNewObj()
return (function(){
newObj.on('selectData', function(evt){
///some code
}
)})();
};
Upvotes: 1