在Polymer元素中调用函数

Zvi*_*arp 1 javascript polymer firebase-polymer polymer-1.0

我很难在聚合物元素中调用函数.我知道你需要使用this.functionName();它,它的工作原理.

但当我在这样的setTimeout中它:runSoon = setTimeout(this.runNow(), 12000);它运行时没有等待.如果我这样写:runSoon = setTimeout(function(){this.runNow()}, 12000);它给我一个错误信息:Uncaught TypeError: this.runNow is not a function.

此外,当我在Firebase中使用this.functionName时它可以工作,但是在"forEach"中,就像在这个例子中一样,它给出了我的错误Uncaught TypeError: this.myFunction is not a function:

ref.once('value', function(snapshot) {
  snapshot.forEach(function(child) {
    this.myFunction();
  });
});
Run Code Online (Sandbox Code Playgroud)

谢谢

Gün*_*uer 5

应该没有 ()

runSoon = setTimeout(this.runNow, 12000);
Run Code Online (Sandbox Code Playgroud)

这样你就可以将参考传递给函数 this.runNow

runSoon = setTimeout(this.runNow(), 12000);
Run Code Online (Sandbox Code Playgroud)

将结果传递this.runNow()setTimeout(...)

  • 尝试`this.runNow.bind(this)`而不仅仅是`this.runNow` (4认同)