Underline bindAll: maintaining the context of 'this'

I am having problems saving uploader as this context when calling onSubmit . Can any JS gurus help?

 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 with the following error:

 Uncaught TypeError: Cannot read property 'bind' of undefined 

Example: http://jsfiddle.net/WilsonPage/BE3Lp/5/

+4
source share
2 answers

Solution: http://jsfiddle.net/WilsonPage/BE3Lp/41/

A few important things I discovered:

  • Before the function is assigned, _.bindAll() must be called.
  • The first argument should be the object or this that you want to bind.
  • The following arguments must be the names of the functions present in the object ( this ), and they must be in string form!
  • If you want to bind all the functions in an object ( this ), omit any function names and specify the object ( this ) as the only argument, for example. _.bindAll(this)

Hope this helps some embarrassed looks like me!

+4
source

Using call or apply , you can specify a 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.net/WDTBV/1/

+1
source

All Articles