Lor*_*o B 6 javascript backbone.js marionette
我的目标 是创建一个可以接收可变数量的视图并基于它们的自定义布局(流布局),它根据需要创建区域,并在这些区域内显示传入的视图.可以安排视图垂直或水平.
要求
布局有一个模板,其中最初未定义区域.它只包含一个包装器(data-role="region-wrapper"),其中将添加添加的区域.
我的方法.
1 - 延伸Marionette.Layout(显然)
2 - 像以下一样Ovveride the construtor
constructor: function(options) {
// call super here...
this.viewList= options.viewList || [];
this._defineRegions(); // see 3
}
Run Code Online (Sandbox Code Playgroud)
3 - 动态定义区域
_defineRegions: function() {
_.each(this.viewList, function(view, index) {
var name = 'flowRegion_' + index;
var definition = { selector: "[data-region='flow-region-" + index + "']" };
this.addRegion(name, definition);
}, this);
},
Run Code Online (Sandbox Code Playgroud)
4 - 在同一布局中的onRender方法中渲染区域和视图
onRender: function() {
_.each(this.viewList, function(view, index) {
// if the view has not been instantiated, instantiate it
// a region is a simple div element
var $regionEl = // creating a region element here based on the index
// append the region here
this.$el.find("[data-role='flow-wrapper']").append($regionEl);
var region = this.getRegion(index); // grab the correct region from this.regionManager
region.show(view);
}, this);
}
Run Code Online (Sandbox Code Playgroud)
这个解决方案似乎有效,但我想知道我是否遵循了有效的解决方案.还有其他方法吗?
也许我没有完全遵循,但我看不出任何理由在这种情况下不能使用collectionView.
子视图都是相同的模式,有data-region='flow-region-",甚至有index.这是一个明显的收集模式及其观点.
使用collectionView,您可以执行类似的操作,添加/删除子视图,完全重置,关闭等.
如果是这种情况,我肯定会建议使用CollectionView或CompositeView,而不是在这里覆盖Region.
更新
关于删除模型的原因将导致删除视图.
因为Marionette CollectionView有这样的倾听者constructor:
this.listenTo(this.collection, "remove", this.removeItemView, this);
Run Code Online (Sandbox Code Playgroud)在运行时添加区域.
尽管我之前没有这样做,但它完全合法.布局具有原型方法addRegion(name, definition),因此任何布局实例都应该能够在运行时添加/删除区域/区域.用法如下:
foo_layout.addRegion({region1: '#region-1'});
Run Code Online (Sandbox Code Playgroud)