在Polymer中使用带有<google-signin>
和<google-signin-aware>
的Google API时,我可以检索日历数据,并将其记录到控制台,但将此数据传递给另一个Polymer函数(在回调之外)不起作用。
我已尝试应用此处显示的答案提示:
https://stackoverflow.com/a/24716257/5779929直接在函数上使用.bind(this)
传递此内容:
handleResponse: function (response) {
console.log('got response: ', response);
this.calendar = response;
},
listUpcomingEvents: function () {
var queryBody = { 'showDeleted': false };
var request = gapi.client.calendar.events.list(queryBody);
request.execute(function (resp) {
console.log(resp);
this.handleResponse(resp);
}.bind(this));
},
上述代码段中对this.handleResponse
的调用给出了:
“Uncaught TypeError:this.handleResponse不是函数”
我试过这样写:
request.execute(this.handleResponse.bind(this));
如下所示:Getting access to a Polymer method inside a function,
但这给了:
“未捕获的TypeError:无法读取未定义的属性'bind'”
答案 0 :(得分:1)
正如在评论中发现的那样,您在不绑定上下文的情况下传递了Polymer对象的函数。调用回调时,上下文不是您的Polymer对象,因此找不到handleResponse
。
通过在传递函数时将上下文与.bind(this)
绑定来解决此问题:
_onApiReady: function() {
...
gapi.client.load('calendar', 'v3', this.listUpcomingEvents.bind(this));
}