How to access a composite view from an item view instance in Backbone Marionette

后端 未结 3 1514
悲哀的现实
悲哀的现实 2021-01-30 17:47

The basic situation is this:

I have a Composite View and an Item View. I construct the Composite view passing it a model and a collection. The model data is used to popu

3条回答
  •  天命终不由人
    2021-01-30 17:54

    Thought I'd share how Andrew Hubbs suggestion helped me. I was trying to display a parent model property inline with my item template. I used Marionette's templateHelpers property to do this in combination with one of Andrew's suggestions.

    I tried to keep the example brief:

    Example Composite template - myView Template:

    Page {{name}}

    Children

      Example item template - myItemTemplate:

      {{name}} is child of: {{getParentName}}
      

      Views:

      App.module( 'App.View', function( View ){
      
          View.MyItemView = Marionette.ItemView.extend({
      
              initialize: function( options ) {
                  this.parentModel = options.parentModel;
              },
      
              template: myItemTemplate,
      
              tagName: 'li',
      
              templateHelpers: function() {
      
                  var view = this;
      
                  return {
                      // Called by item template, returns parent model 'name' property.
                      getParentName: function() {
                          return view.parentModel.get('name');
                      }
      
                  };
              }
      
          });
      
          View.MyView = Marionette.CompositeView.extend({
      
              template: myViewTemplate,
      
              itemView: View.MyItemView,
      
              itemViewContainer: 'ul',
      
              itemViewOptions: function() {
      
                  return { parentModel: this.model };
      
              }
      
          });
      
      });
      

      An example of how this would be implemented:

      // example of how implementation
      // parent model has an attribute called 'children', which is a collection of models
      var children = parent.get('children');
      
      var view = new App.View.MyView( { model: parent, collection: children } );
      
      App.mainRegion.show( view );
      

    提交回复
    热议问题