从子视图向父视图添加新集合

Add new collection to parent view from child view

本文关键字:视图 集合 新集合 添加      更新时间:2023-09-26

我有一个父视图(用于汽车引擎),它包含一个显示选项列表的子视图。其中一个选项是向父视图添加一个新集合。

我的子视图init函数是这样的:

initialize: function (engine) {
    this.engine = engine; //parent object
    this.valves = engine.valves; //may or may not be empty
};

然后我有这个方法,当按钮被按下时添加集合(阀门):

addPerformanceValves: function() {
    var self = this;
    if (this.valves.lentgh == 0) {
        this.valves = new ValveCollection();
        this.valves.url = function() {
            return '/api/engines/auto/performance/parts/' + self.id + '/valves';
        }
    }
    this.$('.performanceParts').show();
}

那么现在我创建了新的集合,我如何将它添加到父集合呢?

有多种方法可以做到这一点。

在层次结构中传递父对象

就像你已经做的那样,你可以从父对象调用一个函数来传递新的集合。

var Child = Backbone.View.extend({
    initialize: function(options) {
        options = options || {};
        this.engine = options.engine; //parent object
        this.valves = engine.valves; //may or may not be empty
    },
    addPerformanceValves: function() {
        var self = this;
        if (this.valves.lentgh == 0) {
            this.valves = new ValveCollection();
            this.valves.url = function() {
                return '/api/engines/auto/performance/parts/' + self.id + '/valves';
            }
            // call the parent
            this.engine.addNewCollection(this.valves);
        }
        this.$('.performanceParts').show();
    }
});
var Parent = Backbone.View.extend({
    addNewCollection: function(collection) {
        // do what you want with the collection
        this.newCollection = collection;
    }
});
<标题> 触发事件

避免强耦合的一种方法是从父视图侦听的子视图触发事件。

var Child = Backbone.View.extend({
    initialize: function(options) {
        options = options || {};
        this.valves = options.valves; //may or may not be empty
    },
    addPerformanceValves: function() {
        var self = this;
        if (this.valves.lentgh == 0) {
            this.valves = new ValveCollection();
            this.valves.url = function() {
                return '/api/engines/auto/performance/parts/' + self.id + '/valves';
            }
            // call the parent
            this.trigger('child:collection', this.valves);
        }
        this.$('.performanceParts').show();
    }
});
var Parent = Backbone.View.extend({
    initialize: function() {
        this.child = new Child({ valves: this.valves });
        // listen to child view events
        this.listenTo(this.child, 'child:collection', this.addNewCollection);
    },
    addNewCollection: function(collection) {
        // do what you want with the collection
        this.newCollection = collection;
    }
});

那么,子视图只拥有它所需要的,没有其他的了。这有助于把责任放在正确的位置。