使用renderTemplate和setupController进行Ember路由

时间:2015-04-04 22:18:17

标签: ember.js ember-data ember-router

我正在构建一个Ember应用程序,以显示一个简单的类似Twitter的标记系统。当用户访问/items时,他或她将看到所有items的列表。当用户访问/tags时,用户会看到tags列表作为链接。当用户点击其中一个链接时,用户应该定向到/tags/:id,并且会看到标记有该特定items的所有tag。然后,用户将能够从ItemsRoute搜索/排序/操纵项目。

如何使用TagRoute使用ItemsController并使用标记的关联items作为模型来呈现items模板?

我在TagRoute尝试过不同的钩子组合,但我找不到有效的配方。我似乎存在一个根本性的误解。

以下是我的相关代码:

router.js.coffee

App.Router.map ()->
  @resource 'items'
  @resource 'tags', ->
    @resource 'tag', path: ':tag_id'

路由/ tag.js.coffee

App.TagRoute = Ember.Route.extend
  model: (params)->
    @get('store').find 'tag', params.tag_id
  controllerName: 'items'
  setupController: (controller, model)->
    @controllerFor('items').set('model', model.items)
  renderTemplate: ->
    @render 'items', ->
      into: 'tags'
      controller: 'items'

模板/ tags.hbs

<ul class="tag-list">
  {{#each tag in model}}
  <li>
    {{#link-to 'tag' tag}}
      {{tag.name}}
    {{/link-to}}
  </li>
  {{/each}}
</ul>

{{outlet}}

模型/ items.js.coffee

App.Item = DS.Model.extend(
  body:       DS.attr('string')
  checked:    DS.attr('boolean')
  tags:       DS.hasMany('tag')
)

模型/ tags.js.coffee

App.Tag = DS.Model.extend(
  name:             DS.attr('string')
  taggings_count:   DS.attr('number')
  items:            DS.hasMany('item')
)

目前,这给了我一个错误:

Error while processing route: tag Cannot assign to read only property 'name' of function () {
        return {
          into: 'tags',
          controller: 'items'
        };
      } TypeError: Cannot assign to read only property 'name' of function () {
        return {
          into: 'tags',
          controller: 'items'
        };
      }

查看Chrome中的Ember Routes Inspector,controllerName属性是唯一覆盖Ember默认值的属性,Ember仍会尝试渲染生成的tag模板。

1 个答案:

答案 0 :(得分:1)

正如ahmed.hoban建议的那样,我已经使用查询参数解决了这个问题。这有助于我避免重复路由和纠结路由器。它击中了数据库,这是不可取的,但我现在还不确定我是否要求这样做。我可以控制整个堆栈,因此我可以在后端进行调整以支持请求。

<强> router.js.coffee

App.Router.map ()->
  @resource 'tags', path: '/', ->
    @resource 'items'

routes / tag.js.coffee - 已删除

<强>模板/ tags.hbs

<ul class="tag-list">
  {{#each tag in model}}
  <li>
    {{#link-to 'items' (query-params tag=tag.id)}}
      {{tag.name}}
    {{/link-to}}
  </li>
  {{/each}}
</ul>

{{outlet}}

<强>控制器/ items.js.coffee

App.ItemsController = Ember.ArrayController.extend(
  needs: 'tags'

  queryParams: ['tag']
  tag: null

  items: (->
    tag = @get 'tag'
    if tag
      @store.find 'item', tag: tag
    else
      @get 'model'
  ).property('tag', 'model')
)
相关问题