我有一条路线需要通过api呼叫加载一组模型。它工作正常,但每当我去另一条路线然后我回到路线Ember正在发射另一组。如何在第一次路由加载时缓存结果? 代码可在此处获取:https://github.com/knusul/embercv/blob/master/app/assets/javascripts/routes/index_route.coffee
App.IndexRoute = Ember.Route.extend
model: (param)->
return Em.RSVP.hash(
card: @store.find('card', 'singleton')
experiences: @store.find('experience')
educations: @store.find('education')
skills: @store.find('skill')
languages: @store.find('language')
hobbies: @store.find('hobby')
).then (hash) ->
return Em.RSVP.hash(hash)
setupController: (controller, model)->
if App.currentUser
@controllerFor('card').set 'model', model.card
@controllerFor('experiences').set 'model', model.experiences
@controllerFor('educations').set 'model', model.educations
@controllerFor('skills').set 'model', model.skills
@controllerFor('languages').set 'model', model.languages
答案 0 :(得分:0)
看起来你在没有任何特定ID的情况下调用#find,即。你要求findAll
。 <{1}}会命中你的适配器,这就是它总是发送一个Ajax调用的原因。
查看Ember数据store documentation:
findAll
方法将始终返回将被解析的承诺 与记录。如果记录已经在商店中,那么承诺将会 立即解决。否则,商店会询问适配器find
找到必要数据的方法。
因此,您可能需要考虑重构代码以针对特定记录ID进行单个#find查询。
答案 1 :(得分:0)
当您执行至少一个find('myModel')
时,获取的数据将存储在记录缓存中,并且可以使用all('myModel')
进行访问而无需新请求。因此,您可以将代码更新为以下内容:
App.ApplicationRoute = Ember.Route.extend
# the model method is called once, when app start
model: (param)->
return Em.RSVP.hash(
card: @store.find('card', 'singleton')
experiences: @store.find('experience')
educations: @store.find('education')
skills: @store.find('skill')
languages: @store.find('language')
hobbies: @store.find('hobby')
).then (hash) ->
return Em.RSVP.hash(hash)
App.IndexRoute = Ember.Route.extend
# because we already loaded all data in application route
# just use all to access the record cache without new ajax requests
model: (param)->
return Em.RSVP.hash(
card: @store.all('card', 'singleton')
experiences: @store.all('experience')
educations: @store.all('education')
skills: @store.all('skill')
languages: @store.all('language')
hobbies: @store.all('hobby')
).then (hash) ->
return Em.RSVP.hash(hash)
setupController: (controller, model)->
if App.currentUser
@controllerFor('card').set 'model', model.card
@controllerFor('experiences').set 'model', model.experiences
@controllerFor('educations').set 'model', model.educations
@controllerFor('skills').set 'model', model.skills
@controllerFor('languages').set 'model', model.languages