使用 Ember.js 按模型类型/对象值选择视图模板 [英] Select view template by model type/object value using Ember.js

查看:16
本文介绍了使用 Ember.js 按模型类型/对象值选择视图模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一个控制器内容数组中存储不同的对象,并使用适当的视图模板渲染每个对象,但理想情况下是相同的视图.

I would like to store different objects in the same controller content array and render each one using an appropriate view template, but ideally the same view.

我正在使用下面的代码输出列表对象.它们目前是相同的,但我希望能够使用不同的.

I am outputting list objects using the code below. They are currently identical, but I would like to be able to use different ones.

<script type="text/x-handlebars">
  {{#each App.simpleRowController}}
    {{view App.SimpleRowView class="simple-row" contentBinding="this"}}
  {{/each}}
</script>

该视图的简化版本如下.我没有包含的其他函数可以用于任何对象,而不管模型如何.所以我最好有一个观点(尽管我已经阅读了一些关于 mixin 的文章,如果没有,它们可能会有所帮助).

A cut-down version of the view is below. The other functions I haven't included could be used an any of the objects, regardless of model. So I would ideally have one view (although I have read some articles about mixins that could help if not).

<script>
  App.SimpleRowView = Em.View.extend({
    templateName: 'simple-row-preview',
  });
</script>

我最初的几个允许不同对象类型的测试结果在简单行预览"中出现了大量条件 - 看起来很糟糕!

My first few tests into allowing different object types ended up with loads of conditions within 'simple-row-preview' - it looked terrible!

有没有什么方法可以动态控制在遍历我的内容数组时使用的模板名称或视图?

Is there any way of dynamically controlling the templateName or view used while iterating over my content array?

更新

非常感谢两位受访者.视图中使用的最终代码如下.我的一些模型很相似,我喜欢能够在我的应用程序中的模板(或某种状态")之间切换的想法.

Thanks very much to the two respondents. The final code in use on the view is below. Some of my models are similar, and I liked the idea of being able to switch between template (or a sort of 'state') in my application.

<script>
  App.SimpleRowView = Em.View.extend({
    templateName: function() {
      return Em.getPath(this, 'content.template');
    }.property('content.template').cacheable(),
    _templateChanged: function() {
      this.rerender();
    }.observes('templateName'),
    // etc.
  });
</script>

推荐答案

您可以将 templateName 设为一个属性,然后根据内容确定要使用的模板.

You can make templateName a property and then work out what template to use based on the content.

例如,这里使用 instanceof 根据对象的类型设置模板:

For example, this uses instanceof to set a template based on the type of object:

App.ItemView = Ember.View.extend({
    templateName: function() {
        if (this.get("content") instanceof App.Foo) {
            return "foo-item";
        } else {
            return "bar-item";
        }
    }.property().cacheable()
});

这是上面的一个工作示例的小提琴:http://jsfiddle.net/rlivsey/QWR6V/

Here's a fiddle with a working example of the above: http://jsfiddle.net/rlivsey/QWR6V/

这篇关于使用 Ember.js 按模型类型/对象值选择视图模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆