Search code examples
javascriptmeteorecmascript-6es6-promisemeteor-blaze

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


I am using a navigator.getBattery() utility for the browser to check laptop battery status and it returns a promise. Below is the small example of my code.

CODE:

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

      });
});

The Console Error I received is as below :

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

How can I access the template variable this.isBatteryCharing inside the promise navigator.getBattery()?


Solution

  • You can use arrow functions to keep the scope:

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

    This way, this still refers to your original object.