Search code examples
filepicker.io

jQuery 'this' in callback


I have the filepicker.io dialog coming up fine but on the success call back I seem to lose my 'this' context.

So my code is like this

var fileProcess ={

 saveFileInfo: function () {
.....process info here
},

selectFile: function () {
        filepicker.pick({ mimetype: 'image/*' }, function (Blob) {
           this.saveFileInfo();
        });

    }

}

So is there something like "context: this" like I can do in an ajax call?


Solution

  • Try creating a new variable named self or me set to the current value of this OUTSIDE your callback. Then, you use closures, so you can access this from your callback through me or self.

    Like:

    this.mesg = "Hello";
    var self = this;
    function handler() {
      alert(self.mesg);
    }
    

    later after a context switch...

    handler(); // Will alert 'Hello'
    

    EDIT: Oh nuts... Just realized that won't work... Try:

    function handler() {
      alert(this.msg);
    }
    var newHandler = handler.bind(this);
    

    Later...

    newHandler();
    

    Function.prototype.bind() takes an object, and returns a function. Whenever the returned function is called, the object passed to bind() is used as this.