Backbone:根据模型值渲染不同的ItemView

时间:2014-05-13 10:16:14

标签: javascript backbone.js model marionette

我设置了一个骨干模型,它使用单个项目视图和模板显示给最终用户。

但是,我在模型中添加了一个新属性,并根据这个新属性的值,我想使用正确的模板/项目视图。

我的骨干代码如下:

InfoWell = Backbone.Model.extend({});

InfoWells = Backbone.Collection.extend({
    model : InfoWell
});

InfoWellView = Backbone.Marionette.ItemView.extend({
    template : "#template-infowell",
    tagName : 'div',
    className : 'alert alert-custom',

initialize: function () {
    this.$el.prop("id", this.model.get("datetime"));
},
});

InfoWellsView = Backbone.Marionette.CompositeView.extend({
    tagName : "div",
    id : "info-well-list",
    template : "#template-infowells",
    itemView : InfoWellView,

});

MainJs.addInitializer(function(options) {
    var aInfoWellsView = new InfoWellsView({
        collection : options.InfoWells
    });
    MainJs.InfoWellsContainer.show(aInfoWellsView);
});

var InfoWells = new InfoWells();

那么,在某个地方(在复合视图中?)我需要单独说出以下内容:

if (this.model.get("infotype") === "blog") {
  // use different template (#template-blogwell)
}

这可能吗?我可以在项目视图中定义两个模板并在那里选择正确的,或者我是否需要两个项目视图,我在复合视图中说哪一个要使用?

谢谢!

2 个答案:

答案 0 :(得分:2)

Marionette JS Docs here中涵盖了这一点:

  

在某些情况下,您需要更改模板   用于视图,基于一些简单的逻辑,如a的值   视图模型中的特定属性。为此,您可以提供   视图上的getTemplate函数,并使用它来返回模板   你需要的。

重复使用您的代码,

InfoWellsView = Backbone.Marionette.CompositeView.extend({
    tagName : "div",
    id : "info-well-list",
    template : "#template-infowells",
    itemView : InfoWellView,
    getTemplate: function () {
        if (this.model.get("infotype") === "blog") {
          // use different template (#template-blogwell)
        }
    }
});

答案 1 :(得分:0)

声明两个templates并在需要时使用它们

 InfoWellView = Backbone.Marionette.ItemView.extend({
    template1 : "#template-infowell",
    template2 : "someOtherTemplate",
    tagName : 'div',
    className : 'alert alert-custom',
相关问题