Auto init and show view within a region on a Marionette Layout

不想你离开。 提交于 2019-12-05 02:48:20

问题


I have a Layout, with a region. When the Layout is initialized, I want it to automatically initialize a pre-set view to do into it's region, and show/close it when the Layout itself is showed/closed.

Current example from https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.layout.md:

AppLayout = Backbone.Marionette.Layout.extend({
  template: "#layout-template",    
  regions: {
    mainRegion: "#menu",
    content: "#content"
  }
});

var layout = new AppLayout();
ParentAppLayout.show(layout); // Render the Layout to a parent
layout.mainRegion.show(new SubView());

This example indicates that the Layout must first be shown, and after I can then init and show the child view. (above, if I show the SubView before the layout is itself shown, nothing will happen, I assume because the selector doesn't exist in the DOM?)

For a re-usable layout, I want to add this send view show into the Layout itself, rather than have to keep on adding it in manually everywhere the view is used. How can this be achieved?

AppLayout = Backbone.Marionette.Layout.extend({
  template: "#layout-template",    
  regions: {
    mainRegion: "#menu",
    content: "#content"
  },
  initalize: function() {
     this.mainRegion.attachView(new SubView());  
  },
  onShow: function() {
     this.mainRegion.show(this.mainRegion.currentView);
  }
});

var layout = new AppLayout();
ParentAppLayout.show(layout); // Render the Layout to a parent, expecting the child view to also be created automatically

This approach however doesn't do anything either - no errors.


回答1:


What about doing this

AppLayout = Backbone.Marionette.Layout.extend({
  template: "#layout-template",    
  regions: {
    mainRegion: "#menu",
    content: "#content"
  },
  onShow: function() {
     this.mainRegion.show(new SubView());
  }
});

var layout = new AppLayout();
ParentAppLayout.show();

Otherwise if creating SubView is expensive you could do it in the initialize like this

initialize: function() {
  this.subView = new SubView();
}

and later use it in the onShow.



来源:https://stackoverflow.com/questions/17363344/auto-init-and-show-view-within-a-region-on-a-marionette-layout

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