Auto init and show view within a region on a Mario

2020-06-25 03:33发布

问题:

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.



标签: marionette