简体   繁体   English

结合使用Google Drive API和Javascript原型

[英]Using Google Drive API with Javascript prototypes

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. 因此,我不想使用Google的Javascript文档中的示例使用全局变量进行标准的复制和粘贴,而是希望使用原型封装所有内容。

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: 那是行不通的,因为回调函数中的this不再是我的GoogleDrive函数,所以我得到:

Uncaught TypeError: Cannot set property 'pickerApiLoaded' of undefined

How would I connect that .onPickerApiLoad to the right scope? 我该如何将.onPickerApiLoad连接到正确的作用域?

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: 在@Jon的回答提示下,我研究了Underscore的bind方法源代码,并使用了call ,所以我尝试执行相同的操作,并使用一个函数返回绑定到所需上下文的原型函数的版本:

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. 这似乎可行(必须确认),但并不那么优雅。

I bet you could get this to work using the bind function of Underscore or Lo-Dash (a drop-in Underscore replacement): 我敢打赌,您可以使用Underscore或Lo-Dash(替代Underscore的替代品)的绑定功能使它起作用:

GoogleDrive.prototype.loadAPI = function() {
    window.gapi.load('picker', {'callback': _.bind(this.onPickerApiLoad, this)});
};

I finally resorted to call and an anonymous function, using which I can pass my own context: 我最终诉诸于call和一个匿名函数,通过它我可以传递自己的上下文:

var that = this;
googleAPI.load('picker', { 'callback': function() {
    return that.onPickerApiLoad.call(that)
} } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM