gpt4 book ai didi

ember.js - 根据模型选择 View 类型

转载 作者:行者123 更新时间:2023-12-03 06:26:29 24 4
gpt4 key购买 nike

我有一个尝试用 Ember 显示的项目列表。对于其中的每一项,我希望能够根据每个模型中的“message_type”字段动态选择用于显示它的 View 类型。

我目前有这样的东西,它完全糟糕并且不可扩展:

{{#each message in controller}}

{{#if message.isImage}}
{{view App.ImageMessageView}}
{{/if}}

....

{{#if message.isVideo}}
{{view App.VideoMessageView}}
{{/if}}

{{/each}}

如何根据 Ember 中模型的字段动态选择 View ?

最佳答案

这是一个类似的问题,显示了两种方法:Collection of objects of multiple models as the iterable content in a template in Ember.js

根据属性或其类型渲染项目

我知道有两种方法可以做到这一点:

  1. 为每个对象添加一个 bool 属性,并使用 Handlebars {{#if}}检查该属性并渲染正确的 View
  2. 扩展 Ember.View 并使用计算属性根据正在渲染的对象类型(基于 Select view template by model type/object value using Ember.js )切换渲染哪个模板

方法1

JS:

App.Post = Ember.Object.extend({
isPost: true
});

App.Bookmark = Ember.Object.extend({
isBookmark: true
});

App.Photo = Ember.Object.extend({
isPhoto: true
});

模板:

<ul>
{{#each item in controller.stream}}
{{#if item.isPost}}
<li>post: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isBookmark}}
<li>bookmark: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{#if item.isPhoto}}
<li>photo: {{item.name}} {{item.publishtime}}</li>
{{/if}}
{{/each}}
</ul>

方法2

JS:

App.StreamItemView = Ember.View.extend({
tagName: "li",
templateName: function() {
var content = this.get('content');
if (content instanceof App.Post) {
return "StreamItemPost";
} else if (content instanceof App.Bookmark) {
return "StreamItemBookmark";
} else if (content instanceof App.Photo) {
return "StreamItemPhoto";
}
}.property(),

_templateChanged: function() {
this.rerender();
}.observes('templateName')
})

模板:

<ul>
{{#each item in controller.streamSorted}}
{{view App.StreamItemView contentBinding=item}}
{{/each}}
</ul>

JSBin example - 未排序列表使用方法1渲染,排序列表使用方法2渲染

关于ember.js - 根据模型选择 View 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com