Robert van Alphen Robert van Alphen - 10 days ago 6
Javascript Question

Calling a Polymer function inside a callback gives 'TypeError .. is not a function'

When using the Google API in Polymer with

<google-signin>
and
<google-signin-aware>
, I can retrieve calendar data, and it logs to the console, but passing this data to another Polymer function (outside of the callback) does not work.

I've tried applying tips from the answer as shown here:
http://stackoverflow.com/a/24716257/5779929 to pass this by using
.bind(this)
directly on the function:

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));
},


The call to
this.handleResponse
in the above snippet gives:


"Uncaught TypeError: this.handleResponse is not a function"


I've tried to write it like this:
request.execute(this.handleResponse.bind(this));
as shown here: Getting access to a Polymer method inside a function,
but that gives:


"Uncaught TypeError: Cannot read property 'bind' of undefined"

Answer

As discovered in comments, you were passing your Polymer object's function without binding the context. When the callback was invoked, the context was not your Polymer object, so handleResponse was not found.

This is resolved by binding the context with .bind(this) when you pass the function:

_onApiReady: function() {
  ...
  gapi.client.load('calendar', 'v3', this.listUpcomingEvents.bind(this));
}