vendredi 18 novembre 2016

Global (window) variable is behaving strangely in Emberjs

I am using Ember-cli in my web app. I have a countdown component to show a countdown timer on UI. Here is my component code.

export default Ember.Component.extend({
    end_time: 0,
    start_time: 0,
    some_id: 0,
    timer: 0, // Show this in UI -  Seconds

    init: function() {
        this._super();
        let end_time = this.get("end_time"),  // 1479476467693
            start_time = this.get("start_time"), // 1479476381491
            some_id = this.get("some_id");
        let wait_time = Math.floor((end_time - start_time)/1000);
        this.set('timer', wait_time);
        let timerName = "timer_" + some_id;
        let _self = this;
        window.initTimer.someTimer[timerName] = setInterval(function() {
            _self.set('timer', wait_time);
            if(wait_time <= 0) {
                clearInterval(window.initTimer.someTimer[timerName]);
            }
            wait_time --;
        }, 1000);
    }
});

This component works fine, if I add this to a single route.

Now, I have added this component to both parent route and child (/:ID) route, since I need to show the component on both templates. In the child (/:ID) template, I have a button to clear the timer. So I have added this code for that button action.

buttonAction: function(some_id) {
            let timerName = "timer_" + some_id;
            clearInterval(window.initTimer.someTimer[timerName]);
        }

Strangely, when the buttonAction is called, the timer on the child template alone is cleared. The timer on parent template keeps running. But both the timer are assigned to a single global variable (window.initTimer.someTimer) and should be cleared when I run clearInterval().

Is there any solution for clearing the timer on both parent route and child route on click of a button, which resides on child template? Couldn't figure out what magic Ember is playing with global variables!!




Aucun commentaire:

Enregistrer un commentaire