我一直在尝试使用Backbone JS制作一个准确的JavaScript计时器,这是我已经得到的:
除了完整的事件之外,它不会发生两次不同的事情,对于我需要做些什么来修复/改进它?
控制台输出:
"tick 10 1"
"tick 10 2"
"tick 10 3"
"tick 10 4"
"tick 10 5"
"tick 10 6"
"tick 10 7"
"tick 10 8"
"tick 10 9"
"complete 10 10"
"complete 10 11"
答案 0 :(得分:1)
您正在拨打start()
两次。创建模型和视图后,一旦在视图中初始化函数。
答案 1 :(得分:1)
您正在start
调用TimerView.initialize
两次,一次调用setTimeout
后再实例化它,这意味着您发生了两个并发的var Timer = Backbone.Model.extend({
/* ... */
});
var TimerView = Backbone.View.extend({
/* ... */
initialize: function () {
this.model.on('tick', function(e){console.log('tick '+e.steps+' '+e.count);}, this);
this.model.on('complete', function(e){console.log('complete '+e.steps+' '+e.count);}, this);
this.model.start(); // <-- One here
}
});
var timer = new Timer();
var timerView = new TimerView({model: timer});
timer.start(); // <-- Another here
循环(而且,您的计时器是移动速度快两倍):
{{1}}
答案 2 :(得分:1)
var TimerView = Backbone.View.extend({
model: Timer,
tagName: 'p',
className: 'timer',
initialize: function () {
this.model.on('tick', function(e){console.log('tick '+e.steps+' '+e.count);}, this);
this.model.on('complete', function(e){console.log('complete '+e.steps+' '+e.count);}, this);
/* this.model.start(); - don't need this */
}
});