I am trying to call a file uploader plugin. When a file is selected, the add
method will be called from library. On calling add
, I need to pass parent method argument opts
with add
method as argument.
Here is piece of code using with RequireJS library.
return {
onFileChoose: function (e, data) {
// I need 'opts' object here
},
start: function (opts) {
$('fileupload').fileupload({
url: '//testbucket.s3.amazonaws.com', // Grabs form's action src
type: 'POST',
autoUpload: true,
dataType: 'xml',
add: this.onFileChoose
});
}
}
I need the opts
object in onFileChoose
.
I tried with
add: function (e, data) {
this.onFileChoose(e, data, opts);
}
Above code produces an error as this.onFileChoose is undefined
.
How to solve this issue?
The problem is inside the callback method, this
is not referring the object having the methods
Use a closure variable
return {
onFileChoose: function (e, data) {
// I need 'opts' object here
},
start: function (opts) {
var self = this;
$('fileupload').fileupload({
url: '//testbucket.s3.amazonaws.com', // Grabs form's action src
type: 'POST',
autoUpload: true,
dataType: 'xml',
add: function (e, data) {
self.onFileChoose(e, data, opts);
}
});
}
}
or use $.proxy()
return {
onFileChoose: function (e, data) {
// I need 'opts' object here
},
start: function (opts) {
$('fileupload').fileupload({
url: '//testbucket.s3.amazonaws.com', // Grabs form's action src
type: 'POST',
autoUpload: true,
dataType: 'xml',
add: $.proxy(function (e, data) {
this.onFileChoose(e, data, opts);
}, this)
});
}
}