在 Promise 中访问模板变量。 [流星+烈焰]

Access Template variable inside a Promise. [Meteor + Blaze]

我正在使用浏览器的 navigator.getBattery() 实用程序来检查笔记本电脑的电池状态,它 returns 是一个承诺。下面是我的代码的小例子。

代码:

Template.Sidebar.onCreated(function(){

    this.isBatteryCharing = new ReactiveVar(0);

    navigator.getBattery().then(function(battery) {

        battery.addEventListener('chargingchange', function(){
          if(battery.charging){
                // access the template variable here. 
                // this.isBatteryCharing.set(battery.charging)
            }
        });

      });
});

我收到的控制台错误如下:

Uncaught (in promise) TypeError: Cannot read property 'set' of undefined

如何访问 promise navigator.getBattery() 中的模板变量 this.isBatteryCharing

您可以使用arrow functions来保持范围:

navigator.getBattery().then((battery) => {

    battery.addEventListener('chargingchange', () => {
      if(battery.charging){
            // access the template variable here. 
            // this.isBatteryCharing.set(battery.charging)
        }
    });

  });

这样,this 仍然引用您的原始对象。