Backbone Marionette: templateHelpers and itemViewOptions

backbone.jsmarionette

I've a problem with Backbone Marionette and ItemView rendering.
I need to pass a value from the Composite View to each of its Item View.
The value is contained correctly in the options array of the Item View, however, I cannot access it from the templateHelpers method.

So I tried to set it as value of my View but when I render the array it returns an "undefined" value.

The Composite View

var TableView = Backbone.Marionette.CompositeView.extend({
....
    itemViewOptions: {
        foo: "bar",
    },

The Item View

var RowView = Backbone.Marionette.ItemView.extend({

template: RowTemplate,
tagName: "tr",
foo: "",

initialize: function(){

    this.foo = this.options.foo;              
},

templateHelpers: {  

     foo: function(){
         return this.foo;
     }

},

What I'm doing wrong? How can I access the value and fetch it to the template? Thank you.

Best Answer

In the templateHelpers functions, the this variable is the object that was retured from the serializeData method. To get the itemViewOptions in to the templateHelpers, then, you need to modify the serializeData method on your item view:


ItemView.extend({

  // ...

  serializeData: function(){
    // call the super method
    var data = Backbone.Marionette.ItemView.prototype.serializeData.apply(this, arguments);

    // augment the data the way you need
    data.foo = this.options.foo;

    // send back your custom data
    return data;
  }


});

This should make your data available in the templateHelpers.

Related Topic