Reputation: 5217
So instead of doing the standard copy & paste from the examples in Google's docs of Javascript with global variables, I want to encapsulate everything using prototypes.
My function starts with this:
define(function (require){
'use strict';
...
but the interesting point at which I am blocked now is:
GoogleDrive.prototype.loadAPI = function() {
window.gapi.load('picker', {'callback': this.onPickerApiLoad});
};
GoogleDrive.prototype.onPickerApiLoad = function() {
this.pickerApiLoaded = true;
this.createPicker();
};
That doesn't work because this
inside the callback is not my GoogleDrive
function any more, so I get:
Uncaught TypeError: Cannot set property 'pickerApiLoaded' of undefined
How would I connect that .onPickerApiLoad
to the right scope?
UPDATE:
Prompted by @Jon's answer, I looked into Underscore's bind
method source code and it uses call
, so I tried to do the same, with a function that returns a version of my prototype function bound to the context I want:
GoogleDrive.prototype.loadAPI = function() {
var that = this;
googleAPI.load('picker', {'callback': function() { return that.onPickerApiLoad.call(that) }});
};
This seems to work (have to confirm), but not that elegant.
Upvotes: 1
Views: 60
Reputation: 5217
I finally resorted to call
and an anonymous function, using which I can pass my own context:
var that = this;
googleAPI.load('picker', { 'callback': function() {
return that.onPickerApiLoad.call(that)
} } );
Upvotes: 0
Reputation: 13727
I bet you could get this to work using the bind function of Underscore or Lo-Dash (a drop-in Underscore replacement):
GoogleDrive.prototype.loadAPI = function() {
window.gapi.load('picker', {'callback': _.bind(this.onPickerApiLoad, this)});
};
Upvotes: 1