Backbone Marionette:templateHelpers和itemViewOptions

Ing*_*gro 11 backbone.js marionette

我有Backbone Marionette和ItemView渲染的问题.我需要将Composite视图中的值传递给每个Item View.该值在项视图的options数组中正确包含,但是,我无法从templateHelpers方法访问它.

所以我尝试将其设置为我的View的值,但是当我渲染数组时,它返回一个"未定义"值.

复合视图

var TableView = Backbone.Marionette.CompositeView.extend({
....
    itemViewOptions: {
        foo: "bar",
    },
Run Code Online (Sandbox Code Playgroud)

物品视图

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

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

initialize: function(){

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

templateHelpers: {  

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

},
Run Code Online (Sandbox Code Playgroud)

我做错了什么?如何访问该值并将其提取到模板?谢谢.

Der*_*ley 29

templateHelpers函数中,this变量是从serializeData方法中退回的对象.要获取itemViewOptionstemplateHelpers,那么,你需要修改的serializeData方法在您的项目视图:


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;
  }


});
Run Code Online (Sandbox Code Playgroud)

这应该使您的数据可用templateHelpers.


小智 12

更简单的解决方案使用构造templateHelpers: function(){return {}},例如:

var RowView = Backbone.Marionette.ItemView.extend({
    // ...
    templateHelpers: function(){  
        return {
            foo: this.foo
        }
    },
    // ...
})
Run Code Online (Sandbox Code Playgroud)

以及与数据一起使用:

var RowView = Backbone.Marionette.ItemView.extend({
    // ...
    templateHelpers: function(){
        var foo = this.foo  // context is view
        return {
            something: function(){ 
                return this.name + " " + foo  // context is data object
            }
        }
    },
    // ...
})
Run Code Online (Sandbox Code Playgroud)

文件:https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.view.md#object-or-function-as-templatehelpers