使用Ember.js按模型类型/对象值选择视图模板 [英] Select view template by model type/object value using 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>
下面是视图的缩减版本。我没有包括的其他功能可以用于任何对象,无论型号如何。所以我最好有一个视图(虽然我已经阅读了一些关于mixins的文章,如果没有,可以帮助)。
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>
我的前几个允许不同对象类型的测试最终在simple-row-预览' - 看起来很可怕!
My first few tests into allowing different object types ended up with loads of conditions within 'simple-row-preview' - it looked terrible!
有没有办法动态控制在迭代我的内容数组时使用的templateName或者view?
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屋!