为什么这个Route的模型仅在3个案例中的2个中更新? - Ember.js 2.3

时间:2016-01-30 15:34:36

标签: javascript ember.js model routes navigation

我正在使用Ember.js 2.3。我的父母Route看起来像这样:

App.AppRoute = Ember.Route.extend
  model: ->
    Ember.RSVP.hash
      projects: @store.findAll "project"
      clients: @store.findAll "client"
      consultants: @store.findAll "consultant"
      practiceAreas: @store.findAll("practice_area").then (practice_areas) ->
        practice_areas.sortBy "displayName"

我有一个孩子Route看起来像:

App.AppProjectRoute = Ember.Route.extend
  model: (params) ->
    hash = @modelFor "app"
    hash["project"] = @store.findRecord "project", params.project_id
      .then (p) -> p
    hash["workWeeks"] = @store.query "work-week", project_id: params.project_id
      .then (weeks) -> weeks
    console.log _.keys hash
    Ember.RSVP.hash hash

Route的模板包含:

  <hr/>
  {{add-consultant project=model.project consultants=model.consultants addConsultant="didAddConsultant"}}
</div>

然后add-consultant组件包含计算属性:

remainingConsultants: Ember.computed "project", "project.consultants.[]", "consultants.[]", ->
  already_involved = @get "project.consultants"
  remaining        = @get "consultants"

  already_involved.forEach (ai) ->
    remaining = remaining.reject (r) -> r.get("id") is ai.get("id")

  remaining.sortBy "displayName"
<案例1

当我直接导航到项目(例如http://localhost/#/app/project/27)时,Route s model挂钩正确地向服务器查询数据并呈现模板和组件。

<案例2

当我直接导航到项目时,请手动更改网址中的项目ID(例如从http://localhost/#/app/project/27改为http://localhost/#/app/project/28,然后按EnterRoute {{ 1}}钩子更新,模板和组件被正确地重新渲染。

<案例3

然而 - 这是我的困惑 - 通过单击链接(例如,使用model帮助程序从项目列表中导航到项目) - 即使我首先如案例1中那样成功访问页面或案例2然后立即导航回同一个项目,我收到一个错误:

{#link-to}

更深入地看,TypeError: already_involved is undefined 本身未定义。

使用@get "project"而不是导致此问题的“直接”导航有什么不同?这是我在定义路线模型层次时犯的错误吗?我错过了某种事件钩子吗?

编辑1:如果有更智能或更惯用的方式来定义这些类型的分层{#link-to}挂钩,那么这可能会避免这个问题吗?

编辑2: model

Router

1 个答案:

答案 0 :(得分:2)

link-to助手或transitionTo / transitionToRoute触发的过渡有两种“模式”。转换可以触发模型挂钩(beforeModelmodelafterModel),也可以不触发。

要跳过模型挂钩,您可以将对象传递给转换,例如{{link-to "Profile" user}}。 Ember.js将此解释为您已经拥有必要的信息,因此会跳过将加载所述信息的钩子。

要强制模型挂钩,您可以将字符串或整数传递给转换,例如{{link-to "Profile" 1}}{{link-to "Profile" user.id}}。这将使用传递给转换的值来填充路径的动态段,并且Ember.js将此解释为尚未加载的数据,从而触发挂钩。

由于模型钩子返回一个哈希值,因此强制钩子以使所有内容都适当加载是有利的。

您可以参考documentation for the model hook了解更多信息。