创建一个接受可变数量的视图(以及因此区域)的布局

时间:2013-12-13 15:37:59

标签: 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
}            

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);
},

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);
}

这个解决方案似乎有效,但我想知道我是否遵循了有效的解决方案。还有其他方法吗?

1 个答案:

答案 0 :(得分:6)

也许我没有完全关注,但我看不出有任何理由在这种情况下不能使用collectionView。

子视图的格式相同,只有data-region='flow-region-",甚至有index。这是一个明显的收集模式及其观点。

使用collectionView,您可以执行类似的操作,添加/删除子视图,完全重置,关闭等。

如果是这种情况,我肯定会建议使用CollectionView或CompositeView,而不是在这里覆盖Region。

<强>更新

  1. 关于删除模型的原因将导致删除视图。

    因为Marionette CollectionView在constructor中有这样的倾听者:

    this.listenTo(this.collection, "remove", this.removeItemView, this);
    
  2. 在运行时添加区域。

    虽然我之前没有这样做,但它完全合法。布局具有原型方法addRegion(name, definition),因此任何布局实例都应该能够在运行时添加/删除区域/区域。用法如下:

    foo_layout.addRegion({region1: '#region-1'});