Search code examples
javascriptrivets.js

DOM not updating when model updates


I am using Rivets.js to make a countdown timer. The countdown timer appears initially, but it does not decrement each time setInterval is called. Why?

Javascript:

function startTimer(minutes) {
    var countdown = (60 * minutes)-1;
    rivets.bind($('#timer'), { countdown: countdown });

    var timer = setInterval(function() {

        countdown--;

        if (countdown < 0) {
            clearInterval(timer);
        }
    }, 1000);
}

HTML:

<div id="timer">{countdown}</div>

Solution

  • You need to bind rivets with an object, otherwise the binding gets lost when you change the variable:

    function startTimer(minutes) {
        var countdownObj = {};
        var countdown = (60 * minutes)-1;
        countdownObj.cd = countdown;
        rivets.bind($('#timer'), { countdown: countdownObj });
    
        var timer = setInterval(function() {
            countdownObj.cd--;
            if (countdownObj.cd < 0) {
                clearInterval(timer);
            }
        }, 1000);
    }
    

    And in your HTML:

    <div id="timer">{countdown.cd}</div>
    

    Check this plunker