0

I've been trying to make an accurate JavaScript timer using Backbone JS this is as far as I've gotten:

Source Code

It works apart from the the complete event fires twice when it shouldn't, any ideas on what I need to do to fix/improve it?

Console Output:

"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"
2
  • Put your code in your question. Commented Jan 2, 2014 at 19:36
  • Looks like you call start twice if I am reading it right. Commented Jan 2, 2014 at 19:36

3 Answers 3

1

You're calling start twice, once in your TimerView.initialize and once again after you instantiate it, meaning you have two concurrent setTimeout loops occurring (and, you're timer is moving twice as fast):

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
Sign up to request clarification or add additional context in comments.

Comments

1

You're calling start() twice. Once after creating the model and view, and once inside your view initialize function.

Comments

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 */
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.