Search code examples
jsrenderjsviews

Using jsviews with array lengths


I have this model:

var taskGroups = 
[
   {name:"Notepad", tasks:[]}
];

My goal is to display each taskGroup in a list in the following format: {Name} {numOfTasks}

If the taskGroup has an empty tasks[] it should not be shown.

Here is my attempt as a jsfiddle: http://jsfiddle.net/ARS2E/

Here is my template:

<script id="tmpl" type="text/x-jsrender">
   {{if tasks.length}}
      <li class="tasklist-item">{{>name}} ({^{:tasks.length}})</li>
   {{/if}}
</script>

Here is my javascript:

var taskGroups = [{name:"Notepad", tasks:[]}];
var lastID=0;

$.templates({ tasklistTemplate: "#tmpl" });
$.link.tasklistTemplate("#tasklist", taskGroups);

$("#btnAdd").on("click", function()
{
    $.observable(taskGroups[0].tasks).insert(0, {taskID:++lastID});
});
$("#btnRemove").on("click", function()
{
    if(taskGroups[0].tasks.length)
    {
        $.observable(taskGroups[0].tasks).remove(0, 1);
    }
});

I've not been able to get this to work and am not sure where I am going wrong. I'd greatly appreciate any help.


Solution

  • Two issues: First, {{if tasks.length}} is not data-bound. If you write {^{if tasks.length}} it will then be data bound.

    Second, in the jsfiddle you had the wrong path for jsrender.js - it is not jquery.render.js.