Question

I am pretty new with MustacheJS and I would like to update the current time using setInterval, but when the setInterval triggers it causes the Mustache template to be empty.

Using .append instead of .html adds another container which I do not want.

JS:

var updateClock = function(){
  var data = {
    'date': getDate(),
    'day': getDay(),
    'hour': getHour(),
    'minute': getMinute()
  };

  var template = $('#template').html();
  $('.container').html(Mustache.render(template, data));
};

updateClock();
setInterval(updateClock, 30000);

HTML:

<div class="container">
    <script type="text/html" id="template">
      <div class="date-container row">
        <div class="large-4 medium-4 small-8 columns">
          <h3>{{date}}</h3>
          <h5>{{day}}</h5>
          <h5>
            <span>{{hour}}</span>
            <span>:</span>
            <span>{{minute}}</span>
          </h5>
      </div>
    </script>
</div>
Was it helpful?

Solution

You are replacing the template with the html in the first updateClock(). Put your <script> template tags outside of the container, or cache the template, as you do not need to get the template every updateClock(). Get it once at the start, and reuse it, then it won't matter if you have replaced it in the HTML i.e.

var template = $('#template').html();
var updateClock = function(){
  var data = {
    'date': getDate(),
    'day': getDay(),
    'hour': getHour(),
    'minute': getMinute()
  };    
  $('.container').html(Mustache.render(template, data));
};

updateClock();
setInterval(updateClock, 30000);

I personally store and cache all my templates namespaced, so as to not pollute the global namespace, something like:

var MoustacheTemplates = 
{
    ClockTemplate :  $('#template').html(),
    AnotherTemplate: $('#anothertemplate').html(),
    AndAnotherOne :  $('#andanothertemplate').html()
};

and then you can use them sort of 'Strongly Typed'

eg

 $('.container').html(Mustache.render(MoustacheTemplates.ClockTemplate, data));

you, of course, have to cache them before you use any of them

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top