从子视图向父视图添加新集合
Add new collection to parent view from child view
我有一个父视图(用于汽车引擎),它包含一个显示选项列表的子视图。其中一个选项是向父视图添加一个新集合。
我的子视图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;
}
});
那么,子视图只拥有它所需要的,没有其他的了。这有助于把责任放在正确的位置。
标题>相关文章:
- 如何在我传递给视图的ViewModel集合中获得jQuery可选对象的值,以作为有序列表进行迭代
- 主干-在对集合进行迭代时将索引传递到视图中
- Backbonejs:在视图中渲染的模型,但在集合中不存在
- backbone.js可以't传递集合中的模型项's查看项目's视图
- 如何将会话数据从集合传递到视图?(Backbone JS/Coffeescapept)
- 何时指定与主干中的集合/视图关联的模型
- 如何在 BackboneJS *木偶* 集合视图中打印行行
- 主干.js绑定到集合“添加”呈现视图两次
- 主干:如何在视图中加载集合(inc-request)
- EmberJS:从集合视图访问项视图
- 我应该如何使用主干视图呈现集合的特定值
- 可以't无法显示视图/集合
- 主干视图集合错误
- 如何在列表和项目视图中呈现骨干集合
- Backbone.js视图可以有一个模型和一个集合吗
- AngularJS在集合项之间更改视图
- 如何在重置视图集合时激发渲染
- 胸部视图集合
- 如何在backbone.js中渲染带有额外值的视图集合
- 主干视图集合.each()错误