Reputation: 15349
I have this js:
(function () {
Namespace = {
settings: {
myVar: 'test'
},
init: function() {
var memberSearchFrm = document.getElementById('memberSearch');
memberSearchFrm.onsubmit = function() {
this.someOtherFunction(); // doesn't work
console.log(this.settings.myVar); // doesn't work
}
},
someOtherFunction: function() {
console.log('test');
}
}
Namespace.init();
})();
I'm losing the context of 'this' when I go into my onSubmit function. Can you help me understand why this is happening and how to work around this situation?
Upvotes: 1
Views: 161
Reputation: 9635
I ran into this same issue with closures and made this fiddle to experiment with different ways to call other functions in a closure.
I finally settled with this format:
(function () {
var obj = {
settings: {
myVar: 'test'
},
init: function() {
var memberSearchFrm = document.getElementById('memberSearch');
memberSearchFrm.onsubmit = function() {
obj.someOtherFunction();
console.log(obj.settings.myVar);
}
},
someOtherFunction: function() {
console.log('test');
}
}
obj.init();
})();
Upvotes: 1
Reputation: 227310
Inside memberSearchFrm.onsubmit
, this
refers to memberSearchFrm
, not to the object you want. You need to save a reference to this
.
init: function() {
var that = this;
var memberSearchFrm = document.getElementById('memberSearch');
memberSearchFrm.onsubmit = function() {
that.someOtherFunction();
console.log(that.settings.myVar);
}
},
Upvotes: 3
Reputation: 1016
Try the this that trick.
Before you closure set a variable called 'that' to this.
var that = this;
Then use that in you closure. The problem you have having is that the closure is attached to you DOM node and not your object. So when you closure was called this had the value of the DOM node.
Upvotes: 3