I am having issues attempting to preserve uploader
as the this
context when onSubmit
is called. Can any JS gurus help out?
uploader: {
init: function(){
var that = this;
var fileUploader = new Uploader.FileUploaderBasic({
button : $("#upload-btn")[0],
action : "/filesCollection",
onSubmit : that.onSubmit
});
_.bindAll(this, this.onSubmit); // attempting to bind 'this'
},
onSubmit: function(id, fileName){
console.log(this); // still refers to 'fileUploader' object :(
}
}
Results in the following error:
Uncaught TypeError: Cannot read property 'bind' of undefined
Example: /
I am having issues attempting to preserve uploader
as the this
context when onSubmit
is called. Can any JS gurus help out?
uploader: {
init: function(){
var that = this;
var fileUploader = new Uploader.FileUploaderBasic({
button : $("#upload-btn")[0],
action : "/filesCollection",
onSubmit : that.onSubmit
});
_.bindAll(this, this.onSubmit); // attempting to bind 'this'
},
onSubmit: function(id, fileName){
console.log(this); // still refers to 'fileUploader' object :(
}
}
Results in the following error:
Uncaught TypeError: Cannot read property 'bind' of undefined
Example: http://jsfiddle/WilsonPage/BE3Lp/5/
Share Improve this question edited Oct 25, 2011 at 10:28 wilsonpage asked Oct 25, 2011 at 10:00 wilsonpagewilsonpage 17.6k23 gold badges105 silver badges150 bronze badges 1-
Came across this really great explanation of
_.bind
and_.bindAll
: blog.bigbinary./2011/08/18/… – Bryan Downing Commented Jun 14, 2013 at 20:02
2 Answers
Reset to default 4Problem Solved: http://jsfiddle/WilsonPage/BE3Lp/41/
Several Important Things I Discovered:
- The
_.bindAll()
must be called before the function is assigned. - The first argument must be the object or
this
you wish to bind. - The arguments that follow must be the names of the functions present within the object (
this
) and they must be in string form! - If you want to bind all functions in the object (
this
) then omit any function names and have the object (this
) as the only argument eg._.bindAll(this)
Hope this helps some confused peeps like me!
By using call
or apply
you can specify the context for this
for any function. This should do the trick (in the fileUploader declaration):
onSubmit: function() {
that.onSubmit.apply(that, arguments);
}
Edit: Updated jsfiddle: http://jsfiddle/WDTBV/1/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744994363a4605097.html
评论列表(0条)