问题描述
我有一个父视图(用于汽车引擎),其中包含一个子视图,该子视图显示了一个选项列表.选项之一是将新集合添加到父视图.
I have a parent view (which is for car engines) that contains a child view which displays a list of options. One of the options is to add a new collection to the parent view.
我的子视图初始化函数如下:
My child view init function looks like this:
initialize: function (engine) {
this.engine = engine; //parent object
this.valves = engine.valves; //may or may not be empty
};
然后我有这种方法,可以在按下按钮时添加集合(阀门):
Then I have this method that adds the collection(valves) when a button is pressed:
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();
}
现在,我创建了新集合,如何将其添加到父集合中?
So now that I created the new collection, how do I add it to the parent?
推荐答案
有多种实现方法.
就像您已经在做的一样,您可以从父对象调用一个函数来传递新集合.
Like you're already doing, you could call a function from the parent object to pass the new collection.
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;
}
});
触发事件
一种避免强耦合的方法是从父视图正在监听的子视图中触发事件.
Triggering events
One way to avoid strong coupling is to trigger events from the child view, to which the parent is listening.
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;
}
});
然后,子视图仅具有所需的内容,仅此而已.这有助于将责任保持在正确的位置.
Then, the child view only has what it needs and nothing more. It help to keep responsibilities at the right place.
这篇关于从子视图向父视图添加新集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!