Search code examples
backbone.jsbackbone-views

Proper way to create a collection list view in Backbone


I'm currently learning Backbone.js and I'm having a hard time learning how to properly use Views (since I have experienced when it comes to MVC), so here is what I'm trying to do:

templates:

    <script type="text/template" id="todolist-template">
        <ul></ul>
    </script>
    <script type="text/template" id="todo-template">
        <li>
            <%= item.name %>
            <%= item.description %>
            <%= item.priority %>
        </li>
    </script>

html:

<div id="container"></div>

Views:

var TodoView = Backbone.View.extend({
    tagName: 'li',
    className: 'todo',
    initialize: function() {
        this.template = _.template($('#todo-template').html());
        this.render();
    },
    render: function() {
        this.$el.html(this.template({item: this.model}));
        return this;
    }
});

var TodoListView = Backbone.View.extend({
    el: '#container',
    tagName: 'ul',
    className: 'todolist',
    initialize: function() {
        this.template = _.template($('#todolist-template').html());
        this.render();
    },
    render: function() {
        that = this;
        this.$el.empty();
        this.$el.append(this.template());
        this.collection.each(function(model) {
            that.$el.append(new TodoView({model: model.toJSON()}));
        });
        return this;
    }
});

Models and Collections:

var Todo = Backbone.Model.extend({
    defaults : {
        name : '',
        priority: '',
        description: ''
    }
});

var TodoList = Backbone.Collection.extend({
    model: Todo
});

var todoList = new app.TodoList([
    new Todo({
        name: 'unclog the sink',
        priority: '10',
        description: 'FIX THE SINK!!!'
    }),
    new Todo({
        name: 'get bread',
        priority: '0',
        description: 'We are out of bread, go get some'
    }),
    new Todo({
        name: 'get milk',
        priority: '2',
        description: 'We are out of milk, go get some'
    })
]);

"misc":

$(function() {
    new HeaderView();
    new TodoListView({collection: todoList});
    router = new AppRouter();
    Backbone.history.start();
});

What I'm trying to do is to create a ul which will then get populated with lis that contain the collection's data. I've been trying to fix/debug this code for a while now (at least 3 hours) but I'm constantly hitting errors or wrong results, so please someone explain to me the proper way of implementing this.

edit (resulting HTML):

<div id="container">
    <ul></ul>
</div>

Solution

  • At least one problem lies here:

    that.$el.append(new TodoView({model: model.toJSON()}));
    

    Should be

    that.$el.append(new TodoView({model: model.toJSON()}).render().el);
    

    Since you can't append a view to $el, but rather you should be appending the rendered html