Backbone Layout Manager渲染项目列表

时间:2014-02-25 20:40:21

标签: backbone.js handlebars.js backbone-layout-manager

我是骨干和骨干布局管理员的新手。我正在尝试呈现联系人列表。这是一段代码

var ContactListView = Backbone.Layout.extend({
    tagName: 'li',

    initialize: function (){
        console.log('ContactListView init');
        this.render();
    },

    render: function (){
        console.log('Rendering all items in the contact list');
        _(this.collection.models).each(function (contact){
            var contactlistitem = new ContactListItemView({model: contact});
            self.$el.append(contactlistitem.el);
        });
    }
});

var ContactListItemView = Backbone.Layout.extend({
    initialize: function (){
        this.render();
    },

    render: function (){
        console.log('called');
        var template = Handlebars.compile($('#contact-list-item').html());
        this.el.html(template(this.model));
    }
});

当我导航到页面时,控制台记录“ContactListView init”,但不输出“渲染联系人列表中的所有项目”。这是为什么?

1 个答案:

答案 0 :(得分:0)

如果this.collectionBackbone.Collection对象,则应使用

this.collection.each(function (contact) {
  // work here
});

您的渲染功能看起来像这样(inspired by the LayoutManager docs):

beforeRender: function (){
    console.log('Rendering all items in the contact list');
    var self = this;
    this.collection.each(function (contact) {
        var contactlistitem = new ContactListItemView({model: contact});
        self.insertView(contactlistitem);
    });
}

代码中的其他位置,可能在控制器或路由器中,您将需要这样的代码来创建集合布局:

// Create an instance of the list view.
var layout = new ContactListView();

// Insert into the Document.
layout.$el.appendTo("body");

// Render the View with the contacts collection.
layout.render({ collection: myCollection });