1

我是主干和handlebars.js 的新手。我正在尝试以编程方式将新项目添加到集合中,并且我希望主干使用 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>
4

1 回答 1

2

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

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

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

于 2012-11-15T21:06:46.320 回答