Dynamically add regions to Marionette layout

依然范特西╮ 提交于 2019-12-03 12:40:45

Marionette v1.0 (v1.0.2 is latest, right now) supports dynamic regions in Layouts.


var MyLayout = Marionette.Layout.extend({
  template: "#some-template"
});

var layout = new MyLayout();
layout.render();

layout.addRegion("someRegion", "#some-element");

layout.someRegion.show(new MyView());

In one of my projects, I faced a similar issue. I needed to create a form dynamically, i.e the form would contain different field views that could not be determined prior runtime. I needed the fields to be Marionette views because they had pretty complicated behaviour.

The way I have done it in Marionette 1.4 in CoffeeScript:

  class Module.AdditionalOptionsLayout extends Marionette.Layout
    tagName: 'form'

    initialize: (options = {}) ->
      @_fieldViews = options.fieldViews || []

    onRender: ->
      @_showFields @_fieldViews

    _showFields: (fieldViews) ->
      fieldViews.forEach (fieldView) => @_addRegion().show fieldView

    _addRegion: ->
      regionClass = _.uniqueId('field-region__')
      @$el.append $("<div class=\"#{regionClass}\"></div>")
      @addRegion regionClass, '.' + regionClass

Please, let me know if it needs further explanation or I can clarify this in JS. I am also aware that it is a late answer, however, hope somebody could find it still useful. Also, note - the answer is relevant only for Marionette 1.x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!