簡體   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