Reputation: 2476
I have a mootools class that uploads a file using XHR:
var foo = new Class({
initialize: function() {
this.bar = 'value';
},
upload: function() {
// This method uploads a file
….
xhr.addEventListener('load', this.uploadComplete, false);
….
},
uploadComplete: function() {
// Is getting called on completion of file upload
console.log(this.bar); // undefined, but I want to to be 'value'
}
});
I would like to access this.bar
in the uploadComplete
method but this
is not getting passed through in xhr.addEventListener('load', this.uploadComplete, false);
Any help is appreciated.
Upvotes: 2
Views: 96
Reputation: 26165
you need to use Function.prototype.bind
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind and http://mootools.net/docs/core/Types/Function#Function:bind - which will set the context of this correctly when the event fires.
xhr.addEventListener('load', this.uploadComplete.bind(this), false);
Upvotes: 4