I am trying to call a function when linkWithPopup
resolves with the following code:
_linkToCurrentUser: function(authId, provider) {
this.user.linkWithPopup(provider).then(function(result) {
console.log("user linked ", result);
this.updateUserInfos(authId); // <-- error: this.updateUserInfos is not a function
}).catch(function(error) {
console.log(error);
});
},
updateUserInfos: function(authId) {
...
}
But it results in this error:
Uncaught TypeError: this.updateUserInfos is not a function
However, the function works when it's outside of the linkWithPopup
function:
_linkToCurrentUser: function(authId, provider) {
this.user.linkWithPopup(provider).then(function(result) {
console.log("user linked ", result);
}).catch(function(error) {
console.log( error);
});
this.updateUserInfos(authId); // <-- works
},
updateUserInfos: function(authId) {
...
}
How do I fix this?
This problem is the context of your callback is not bound to the Polymer object, so it uses the outer context (normally the Window
object) for this
.
You could switch to arrow functions (assuming ES6 is available for you) to automatically bind the Polymer object:
_linkToCurentUser: function(authId, provider) {
this.user.linkWithPopup(provider).then(result => { // <-- bind `this` to Polymer object
console.log('user linked', result);
this.updateUserInfos(authId);
})
...
}
Or you could use Function.prototype.bind()
to bind the context to the Polymer object:
_linkToCurentUser: function(authId, provider) {
this.user.linkWithPopup(provider).then(function(result) {
console.log('user linked', result);
this.updateUserInfos(authId);
}.bind(this)) // <-- bind `this` to Polymer object
...
}
Or you could pass in a reference:
_linkToCurentUser: function(authId, provider) {
var self = this; // <-- cache reference for use in callback
this.user.linkWithPopup(provider).then(function(result) {
console.log('user linked', result);
self.updateUserInfos(authId);
})
...
}