Backbone和Handlebars在将项目添加到集合后呈现问题

时间:2012-11-15 21:00:46

标签: backbone.js handlebars.js

我是骨干和handlebars.js的新手。我正在尝试以编程方式将新Item添加到集合中,我希望使用Render渲染集合。

我做错了什么?

var Item = Backbone.Model.extend({
    defaults: {
    }
});

var List = Backbone.Collection.extend({
    model: Item
});

var ListView = Backbone.View.extend({
    el: $('BODY'), // el attaches to existing element
    initialize: function () {
        _.bindAll(this, 'render'); // every function that uses 'this' as the current object should be in here

        this.collection = new List();
        this.render();
    },
    render: function () {
        var template = Handlebars.compile($('#screenshot_template').html());
        $(this.el).html(template({
            row: this.collection
        }));
        return this;
    }

});

var listView = new ListView();
window.screenshots = listView;
window.screenshots.collection.add({
    myurl: 'http://placehold.it/350x150'
});

我的车把模板如下:

<script id="screenshot_template" type="text/x-handlebars-template">
    {{#each row}}
    <div><img src="{{this.myurl}}"></div>
    {{/each }}
</script>

1 个答案:

答案 0 :(得分:2)

为视图添加一个侦听器,以便它知道集合何时触发add事件 - 通常在视图的initialize函数中完成:

this.collection.on('add', this.render);

显然,您需要在实例化集合后添加它。