Heyho
我在Ember写的倒计时有点问题。更确切地说,当它击中0时停止我的计数器。
首先......我正在使用
Ember Version
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()
我在控制器内开始倒计时(播放动作)。 倒计时倒计时,但它不会停止:(
onTick()中的self.stop()调用根本不做任何事情......
我尝试在我的控制器中使用其他操作停止倒计时,这样可以正常工作:/
任何想法如何解决这个问题?
干杯迈克尔
答案 0 :(得分:1)
我已采取礼貌或根据您提供的代码编写倒计时服务,允许您启动,重置和停止倒计时。我的代码假设您使用的是Ember CLI,但我已经包含了一个考虑旧ES5语法的JSBin。
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供你玩。