javascriptdust.jsclient-side-templatingtemplating-engine

Uncaught TypeError: Cannot read property 'substr' of undefined Dustjs


I am trying to learn javascript templating, namely dustjs but I encountered problem which I think is so basic even google cannot answer it :)

Here is code in it's simplest form

      <button class="getData" onClick="clicker()">Get Data</button>

      <ul class="vodka">
      <script id="vodka" type="text/x-template">

       <li>{name}</li>

       </script>
       </ul>

Javascript

   window.addEventListener("load", clicker)

function clicker()
{
    getData();
}

function getData()
{
var data = {name:"Vodka", degree:97}
var source = $("#vodka").html();
var template = dust.compile(source, "vodkaTemplate");
dust.loadSource(template);
dust.render("vodkaTemplate", data, function(err, res){
            $(".vodka").html(res)
            console.log(res)
})
}

During initialization template renders perfectly but clicking on button causes error

Uncaught TypeError: Cannot read property 'substr' of undefined

What am I doing wrong?


Solution

  • You render the template once on load (line 1 of your script).

    When you render the template, you replace the contents of <ul class="vodka"> with the rendered template.

    However, you have placed your template source inside this container as well, for whatever reason. The template source is removed from the DOM on the first render, since it was replaced with the rendered content. So when you try to render the template a second time, this line sets source to null:

    var source = $("#vodka").html(); // #vodka does not exist anymore
    

    And Dust errors out because it is trying to compile null to a template.