繁体   English   中英

视图中的Backbone.js多个模型

[英]Backbone.js Multiple Models within a View

是否可以创建一个视图,该视图列出绑定到不同模型的集合? 还可以使用排序功能吗?

例如,我有一个“销售”和“帐户”模型,并想以这些部门中所有工作人员的名字作为视角。

谢谢

当然。 您通常要做的是结合使用以下事件:在集合上应用事件侦听器,创建代表每个模型的小子视图,并通过该子视图绑定模型事件处理程序。

BigView = Backbone.View.extend({
    el: 'ul',  // This view is a <ul> and we'll be adding the model views
    initialize: function() {
        // This collection represents the collection you passed in
        // For our purpose lets say it was a SalesCollection
        this.collection.on('reset', this.addAllSales, this);
        this.collection.on('add', this.addSale, this);
    },
    addAllSales: function() {
        var that = this;
        this.collection.each(function(sale) {
            that.addSale(sale);
        });
    }
    addSale: function(model) {
        var view = new Subview({
            'model': model
        });
        this.$el.append(view.render().el);
    }
});

SaleView = Backbone.View.extend({
    initialize: function() {
        this.model.on('change', this.something, this);
    },
    render: function() {
        this.$el.html();  // Or whatever else you need to do to represent a sale as view
        return this;
    }
    something: function(model) {
        // Code for something
    }
});

因此,在此示例中,您基本上具有包含集合(例如销售)的主视图。 重置销售集合后,它将触发addAllSales() 每次将销售添加到集合中,我们都会添加一个代表特定模型(销售模型)的子视图。 在此子视图中,我们负责将事件绑定到模型更改,然后执行一些操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM