Marionette.CompositeView, how to pass parameters to Marionette.ItemView

左心房为你撑大大i 提交于 2019-12-03 09:27:17

问题


I would like to access the app.vent from Marionette.ItemView.

Maybe an option could be to pass a parameter (app.vent) to Marionette.ItemView from Marionette.CompositeView.

Here my code:

// view/compositeView.js
define([
    'marionette',
    'views/item'
], function (Marionette, itemView) {
    var ListView = Marionette.CompositeView.extend({ 
        itemView: itemView
    });
});

Any ideas?

P.S.:
I cannot access the app from itemView because there is a problem of circular dependency.

app -> view/compositeView -> view/itemView

回答1:


v0.9 added an itemOptions attribute that can be used for this. It can either be an object literal or a function that returns an object literal.



Backbone.Marionette.CompositeView.extend({
  itemView: MyItemViewType,

  itemViewOptions: {
    some: "option",
    goes: "here"
  }

});

All of the key: "value" pairs that are returned by this attribute will be supplied to the itemview's options in teh initializer


Backbone.Marionette.ItemView.extend({
  initialize: function(options){
    options.some; //=> "option"
    options.goes; //=> "here"
  }
});

Additionally, if you need to run specific code for each itemView instance that is built, you can override the buildItemView method to provide custom creation of the item view for each object in the collection.


  buildItemView: function(item, ItemView){

    // do custom stuff here

    var view = new ItemView({
      model: item,
      // add your own options here

    });

    // more custom code working off the view instance

    return view;
  },

For more information, see:

  • the change log for v0.9
  • the CollectionView documentation for itemViewOptions - note that CompositeView extends from CollectionView, so all CollectionView docs are valid for CompositeView as well
  • the buildItemView annotated source code



回答2:


Since Marionette v2.0.0, childViewOptions is used instead of itemViewOptions to pass parameters to the child view:

var MyCompositeView = Marionette.CompositeView.extend({
  childView: MyChildView,
  childViewOptions: function(model, index) {
    return {
      vent: this.options.vent
    }
  }
});

var MyChildView = Marionette.ItemView.extend({
  initialize: function(options) {
      // var events = options.vent;
  }
});

new MyCompositeView({ vent: app.vent, collection: myCollection});

But to work with events, lets use Marionette.Radio instead of passing app.vent to the view.



来源:https://stackoverflow.com/questions/11273115/marionette-compositeview-how-to-pass-parameters-to-marionette-itemview

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