如何使用 Ember ArrayController 获取对象集合?
Posted
技术标签:
【中文标题】如何使用 Ember ArrayController 获取对象集合?【英文标题】:How do I fetch a collection of objects using Ember ArrayController? 【发布时间】:2015-06-30 09:22:23 【问题描述】:我目前无法获得一系列奖项,我在获得这个系列时做错了什么?
我不断收到以下错误:
错误:处理路由时出错:奖励断言失败:ArrayController 期望 model
实现 Ember.Array mixin。这通常可以通过使用 `Ember.A()
router.coffee
...
Router.map ->
# Contests
@resource 'contests'
@resource 'contest', path: '/contests/:contest_id'
# Awards
@resource 'awards', path: '/contests/:contest_id/awards'
@resource 'award', path: '/contests/:contest_id/awards/:award_id'
# Ads
@resource 'ads', path: '/contests/:contest_id/ads'
@resource 'ad', path: '/contests/:contest_id/ads/:ad_id'
...
award.coffee 模型
`import DS from 'ember-data'`
AwardModel = DS.Model.extend
# Attributes
description: DS.attr 'string'
amount: DS.attr 'string'
adId: DS.attr 'string'
adType: DS.attr 'string'
state: DS.attr 'string'
thumbnail: "http://placehold.it/290x218"
# Relationships
ad: DS.belongsTo 'ad', async: true
contest: DS.belongsTo 'contest', async: true
`export default AwardModel`
contest.coffee 模型
`import DS from 'ember-data'`
ContestModel = DS.Model.extend
# Attributes
title: DS.attr 'string'
truncatedTitle: DS.attr 'string'
state: DS.attr 'string'
totalAwards: DS.attr 'string'
totalAds: DS.attr 'string'
startsOn: DS.attr 'date'
endsOn: DS.attr 'string'
daysLeft: DS.attr 'string'
thumbnail: DS.attr 'string'
createdAt: DS.attr 'date'
# Relationships
ads: DS.hasMany 'ad', async: true
awards: DS.hasMany 'award', async: true
`export default ContestModel`
awards.coffee 控制器
`import Ember from 'ember'`
AwardsController = Ember.ArrayController.extend
videoAwards: '',
printAwards: '',
setAwards: (type) ->
awards = @filter((award) ->
award.get('adType') == type.capitalize()
)
@set(type + 'Awards', awards)
actions:
sortAwardsByType: ->
@setAwards('video')
@setAwards('print')
# TODO: find out why this is not working
# ['video', 'print'].forEach (type) ->
# @setAwards(type)
`export default AwardsController`
awards.coffee 路线文件
`import Ember from 'ember'`
`import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin'`
AwardsRoute = Ember.Route.extend AuthenticatedRouteMixin,
model: ->
# How to fetch the awards of the given contest here with ember data
setupController: (controller, model) ->
controller.set('model', model)
controller.send('sortAwardsbyType')
`export default AwardsRoute`
【问题讨论】:
根据您遇到的错误,您可能有prototype extensions disabled。您需要启用它们或采取适当的措施来确保您使用Ember.A()
调用来包装您的数组。
【参考方案1】:
这可行:
// awards route
model: (params) ->
@store.find('contest', params.contest_id).then((contest) ->
contest.get('awards')
)
更多关于承诺链here.
然后您可以在奖励控制器中对模型进行过滤。
【讨论】:
以上是关于如何使用 Ember ArrayController 获取对象集合?的主要内容,如果未能解决你的问题,请参考以下文章
如何以及何时使用 Ember.Application 注册和注入方法?
ember-data-url-templates - 如何在Ember 3中使用快照API