Search code examples
javascriptjsonractivejs

RactiveJS and time conditional DOM


I have page wich displays time-dependent text-snippets from a json with Ractive.js. After initialisation, I want to check every minute, if the stop-time, which is stored in the json, is due. Then the text-snippet should be hidden.

Things I've tried:

{{#if time_due > Date.time()}}
do whatever
{{/if}}

The above doesn't work for me. I also played around with computed properties of Ractive.js, but that didn't work either. Has somebody a good idea and/or can help me?


Solution

  • Ractive won't recompute expressions (like time_due > Date.now()) unless it thinks something has changed. The easy solution is to assign the current time to a data property and update it periodically:

    var ractive = new Ractive({
      el: 'main',
      template: '#template',
      data: {
        timeNow: Date.now(),
        displayUntil: Date.now() + 5000
      }
    });
    
    setInterval( function () {
      ractive.set( 'timeNow', Date.now() );
    }, 500 );
    <script src='http://cdn.ractivejs.org/edge/ractive.js'></script>
    
    <main></main>
    
    <script id='template' tyle='text/html'>
      {{#if timeNow < displayUntil}}
        <p>now you see me</p>
      {{else}}
        <p>now you don't</p>
      {{/if}}
      
      <p>(time remaining: {{displayUntil - timeNow}}ms)</p>
    </script>