如何在linkWithPopup函数之后调用函数

时间:2017-03-09 18:02:36

标签: polymer web-component

我试图在linkWithPopup使用以下代码解析时调用函数:

_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) {
  ...
}

但它导致了这个错误:

 Uncaught TypeError: this.updateUserInfos is not a function

但是,当函数在linkWithPopup函数之外时,该函数有效:

_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) {
  ...
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

此问题是您的回调的上下文未绑定到Polymer对象,因此它使用Window的外部上下文(通常是this对象)。

您可以切换到arrow functions(假设ES6可用),以自动绑定Polymer对象:

_linkToCurentUser: function(authId, provider) {
  this.user.linkWithPopup(provider).then(result => { // <-- bind `this` to Polymer object
    console.log('user linked', result);
    this.updateUserInfos(authId);
  })
  ...
}

或者您可以使用Function.prototype.bind()将上下文绑定到Polymer对象:

_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
  ...
}

或者您可以传递参考:

_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);
  })
  ...
}