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

后端 未结 3 1464
悲哀的现实
悲哀的现实 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 18:13

    If you want to access data from the parent CompositeView you can do a number of different things.

    1. Either pass that data directly to the ItemView through the itemViewOptions helper function on the CompositeView. Note: This option has changed to childViewOptions in Marionette 2.

    2. Invoke a method directly on all of the children view from the CompositeView and pass whatever you want into that method.

    3. Trigger an event on or listened for by the ItemView.

    None of these options are directly accessing the parent view from the child but should do what you want. Below is code for how to use each of these approaches to pass the CompositeView's model to the children view.

    // Pass model into ItemView on init
    var MyItemView = Backbone.Marionette.ItemView.extend({
      initialize : function (options) {
        this.parentsModel = options.parentsModel;
      }
    });
    var MyCompView = Backbone.Marionette.CompositeView.extend({
      itemViewOptions : function () { return { parentsModel: this.model }; }
      itemView : MyItemView
    });
    
    
    // Invoke function on ItemView, passing data in
    var MyItemView = Backbone.Marionette.ItemView.extend({
      doSomethingWithParent : function (parentModel) {
        // do cool thing with parentModel
      }
    });
    var MyCompView = Backbone.Marionette.CompositeView.extend({
      itemView : MyItemView,
      onRender : function () {
        this.children.call("doSomethingWithParent", this.model);
      }
    });
    
    
    // Trigger event that ItemView knows about
    var MyItemView = Backbone.Marionette.ItemView.extend({
      initialize : function () {
        this.listenTo(this, "special:event", function (parentModel) {
          // Do cool things
        });
      }
    });
    var MyCompView = Backbone.Marionette.CompositeView.extend({
      itemView : MyItemView,
      onRender : function () {
        this.children.each(_.bind(function (childView) {
          childView.trigger("special:event", this.model);
         }, this));
      }
    });
    

提交回复
热议问题