Emberjs倒计时-无法停止

Emberjs Countdown - not stoppable

本文关键字:无法停止 倒计时 Emberjs      更新时间:2023-09-26

Heyho

我对我用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();
  }
}

Ember.run.later((倒计时

我正在控制器中开始倒计时(播放动作(。倒计时应该倒计时,但不会停止:(

onTick((中的self.stop((调用根本不起任何作用。。。

我试图用控制器中的另一个操作来停止倒计时,它正在正常工作:/

有什么办法解决这个问题吗??

为Michael 干杯

我已经礼貌地根据您提供的代码编写了倒计时服务,该服务允许您启动、重置和停止倒计时。我的代码假设您使用的是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));
  }
});

我已经在JSBin上提供了一个此实现的示例,供您参考。