简体   繁体   English

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

[英]Backbone: Rendering different ItemViews based on model value

I have a backbone model set up where it uses a single itemview and template to display to the end user. 我有一个骨干模型设置,它使用单个项目视图和模板显示给最终用户。

However, I have added a new attribute into the model, and based on the value of this new attribute I would like to use the correct template/itemview. 但是,我在模型中添加了一个新属性,并根据这个新属性的值,我想使用正确的模板/项目视图。

My backbone code is below: 我的骨干代码如下:

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();

So, somewhere (in the compositeview?) I need to say something alone the lines of: 那么,在某个地方(在复合视图中?)我需要单独说出以下内容:

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

Is this possible? 这可能吗? Can I define two templates in my itemview and choose the correct on there, or do I need two itemviews and I say in my compositeview which one to use? 我可以在项目视图中定义两个模板并在那里选择正确的,或者我是否需要两个项目视图,我在复合视图中说哪一个要使用?

Thank you! 谢谢!

This is covered in the Marionette JS Docs here : 这是覆盖在木偶JS文件在这里

There may be some cases where you need to change the template that is used for a view, based on some simple logic such as the value of a specific attribute in the view's model. 在某些情况下,您需要根据一些简单的逻辑(例如视图模型中特定属性的值)更改用于视图的模板。 To do this, you can provide a getTemplate function on your views and use this to return the template that you need. 为此,您可以在视图上提供getTemplate函数,并使用它来返回所需的模板。

Reusing your code, 重用你的代码,

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

Declare two templates and use them when required 声明两个templates并在需要时使用它们

like 喜欢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM