Search code examples
javascriptractivejs

Override ractivet.set with ractive.animate for a specific keypath


I'm writing a card game and the game state is coming from the server through a websocket. When the client receives the game state, I call ractive.set('game', game).

Inside the game object is a list of users who have money. When their money changes I want the numbers animate so I write:

ractive.observe('game.seats.*.money', function(money, oldmoney, keypath) {
    ractive.animate(keypath, money);
})

Unfortunately this doesn't work. I think it's because by the time I'm observing the update, the game state has already been set to the new value and then animating to the new value looks like nothing.

Is there a way to acheive the effect I'm looking for?


Solution

  • FWIW Ractive does have the ability to animate object hierarchies, so you could call ractive.animate("game', game). See http://jsfiddle.net/hj568b0m/.

    But assuming that you don't want to animate other parts of the model, you could use the observer (which fires before DOM update) to set the value back and then animate it:

    var animating = []
    r.observe('game.seats.*.money', function(money, oldmoney, keypath, index) {
        // the animation update will re-enter the observer,
        // so bail if we are animating this index...
        if ( animating[index] ) { return; }
    
        animating[index] = true;
        r.set(keypath, oldmoney);   
        r.animate(keypath, money).then(function(){
            animating[index] = false;
        });
    });
    

    See http://jsfiddle.net/tyyfmosr/