在Backbone中创建集合列表视图的正确方法

时间:2013-09-17 00:00:12

标签: backbone.js backbone-views

我正在学习Backbone.js而且我很难学习如何正确使用Views(因为我遇到过MVC),所以这就是我要做的:

模板

    <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>

视图

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;
    }
});

模型和收藏

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();
});

我要做的是创建一个ul,然后填充包含该集合数据的li。我一直在尝试修改/调试这段代码一段时间(至少3个小时),但我经常遇到错误或错误的结果,所以请有人向我解释实现这个的正确方法。

编辑(生成HTML)

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

2 个答案:

答案 0 :(得分:4)

这里至少有一个问题:

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

应该是

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

由于您无法将视图附加到$ el,而是应该附加渲染的html

答案 1 :(得分:2)

您的模板中不需要<li>,因为您的视图已将模板包装在这些标记中。如果它仍然不起作用,请检查DOM并在此处发布。同样适用于<ul> ...

另外,我没有看到您将ListView添加到DOM的位置。 render仅对尚未属于DOM的本地元素进行操作。渲染完成后,您必须将其添加到DOM中。