2015-08-04 3 views
0

HeyhoEmberjs Countdown - not stoppable

У меня есть небольшая проблема с моим обратным отсчетом, написанным в Ember. Более точно остановить свой счетчик, когда он попадает 0.

Прежде всего ... Я использую

Ember Версия

DEBUG: Ember     : 1.12.0 

Я создал «сервис» класса с некоторые простые методы обработки обратного отсчета.

interval: function() { 
    return 10; // Time between polls (in ms) 
}.property().readOnly(), 

totalTime: function() { 
    return 5000; // Total Time (in ms) 
}.property(), 

timeDiff: 0, 
timeLeft: function() { 
    return Math.floor((this.get('totalTime') - this.get('timeDiff'))/1000); 
}.property('timeDiff'), 

hasFinished: function() { 
    return this.get('timeLeft') === 0; 
}.property('timeLeft'), 


// Schedules the function `f` to be executed every `interval` time. 
schedule: function(f) { 
    return Ember.run.later(this, function() { 
    f.apply(this); 
    this.set('timer', this.schedule(f)); 
    }, this.get('interval')); 
}, 


// Starts the countdown, i.e. executes the `onTick` function every interval. 
start: function() { 
    this.set('startedAt', new Date()); 
    this.set('timer', this.schedule(this.get('onTick'))); 
}, 


// Stops the countdown 
stop: function() { 
    Ember.run.cancel(this.get('timer')); 
}, 


onTick: function() { 
    let self = this; 
    self.set('timeDiff', new Date() - self.get('startedAt')); 
    if (self.get('hasFinished')) { 
    // TODO: Broken - This should stop the countdown :/ 
    self.stop(); 
    } 
} 

CountDown with Ember.run.later()

Я начинаю обратный отсчет времени в пределах моего контроллера (воспроизведение действия). Обратный отсчет обратный отсчет, как должно, но он просто не останавливается Звонок :(

self.stop() в OnTick() просто ничего не делает вообще ...

Я пытался остановить отсчет с другого действия в мой контроллер и работает, как и должно быть:/

Любые идеи, как решить эту проблему ??

Приветствия Майкл

+0

[Может быть связан] (http://stackoverflow.com/questions/23688238/ember-js-clearinterval-not-working) –

+0

Heyho - thx для ссылки. У меня уже есть рабочее решение с setInterval [gist] (https://gist.github.com/tzhbami7/065bd41f1d45d20dd7e5). Я попытался перенести его на Ember.run.later(), так как я слышал, что это плохая практика использовать setInterval – sufu90

+0

Правильно ли он называет self.stop()? Если не убедиться, что hasFinished в какой-то момент равен нулю, в противном случае он будет продолжать работу, если по какой-либо причине он пропустит ноль. Возможно, попробуйте <= вместо этого. – Spazmoe06

ответ

1

Я взял любезность или письменной форме служба обратного отсчета, основанная на коде вы предоставили возможность запуска, сброса и остановки обратного отсчета. Мой код предполагает, что вы используете Ember CLI, но я включил JSBin, который учитывает старый синтаксис ES5.

app/services/countdown.js

import Ember from 'ember'; 

const { get, set, computed, run } = Ember; 

export default Ember.Service.extend({ 
    init() { 
    set(this, 'totalTime', 10000); 
    set(this, 'tickInterval', 100); 
    set(this, 'timer', null); 
    this.reset(); 
    }, 

    remainingTime: computed('elapsedTime', function() { 
    const remainingTime = get(this, 'totalTime') - get(this, 'elapsedTime'); 
    return (remainingTime > 0) ? remainingTime : 0; 
    }), 

    hasFinished: computed('remainingTime', function() { 
    return get(this, 'remainingTime') === 0; 
    }), 

    reset() { 
    set(this, 'elapsedTime', 0); 
    set(this, 'currentTime', Date.now()); 
    }, 

    start() { 
    this.stop(); 
    set(this, 'currentTime', Date.now()); 
    this.tick(); 
    }, 

    stop() { 
    const timer = get(this, 'timer'); 

    if (timer) { 
     run.cancel(timer); 
     set(this, 'timer', null); 
    } 
    }, 

    tick() { 
    if (get(this, 'hasFinished')) { 
     return; 
    } 

    const tickInterval = get(this, 'tickInterval'); 
    const currentTime = get(this, 'currentTime'); 
    const elapsedTime = get(this, 'elapsedTime'); 
    const now = Date.now(); 

    set(this, 'elapsedTime', elapsedTime + (now - currentTime)); 
    set(this, 'currentTime', now); 
    set(this, 'timer', run.later(this, this.tick, tickInterval)); 
    } 
}); 

Я сделал пример реализации этого available on JSBin для вас игрушка вокруг с.

+0

Holy moly: P Thx много !! Я посмотрю на это немного. – sufu90

+0

Это работает :) thx !!!! – sufu90