Search code examples
backbone.jsviewunderscore.jsbackbone-viewsbackbone-routing

Backbone.js Task App how should grouped view look like


I am developing a task app in Backbone.js for FUN and one of feature is grouped view. Grouped view will display tasks that are grouped according to their done status. Currently i can construct the grouped object from the collection. Constructing the view has become trivial to me. Here is a snapshot of how i want the view to look like

Completed Tasks

- Water the Garden

- Clean my closet

Pending Tasks

- Watch Whose line is it anyway

the JSON after grouping is below

{
    "true": [{
        "Name": "Finished Demo",
        "Done": true,
        "id": "4b3d8d3d-637c-fd5d-034b-b275b5f00e05"
    }, {
        "Name": "This is a new task",
        "Done": true,
        "id": "db5b379f-6f96-346d-4945-baf2d5ac0c76"
    }, {
        "Name": "Clean the closet",
        "Done": true,
        "id": "3b5091e5-a8df-845b-3c6d-2185187eb456"
    }],
    "false": [{
        "Name": "Edited another new task",
        "Done": false,
        "id": "0ee399b2-8fd9-84f2-735e-902d09c625a1"
    }]
}

I can't think of how to construct a template for the UI based on grouped json above. Assuming i am using underscore.js _.template for templating purpose.

  • How should the template look

Solution

  • Keep in mind, true and false are reserved keywords in Javascript. I suggest you don't use it as variable names.

    <ul>
        <% if (finished) { %>
            <% _.each(finished, function (task) { %>
                <li id=<%= task.id %>>
                    <%= task.Name %>
                <input type="checkbox" checked />
                </li>
            <% }); %>
        <% }; %>
        <% if (unfinished) { %>
            <% _.each(unfinished, function (task) { %>
                <li id=<%= task.id %>>
                    <%= task.Name %>
                <input type="checkbox" />
                </li>
            <% }); %>
        <% }; %>
    </ul>
    

    http://jsfiddle.net/theotheo/zJXW8/