0

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

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”,但不会输出“正在渲染联系人列表中的所有项目”。为什么是这样?

4

1 回答 1

0

如果this.collection是一个Backbone.Collection对象,那么你应该使用

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

您的渲染函数将如下所示(受 LayoutManager 文档的启发):

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 });
于 2014-02-25T22:53:20.357 回答