问题描述
My problem is related with the issues #1183 and #1268 of emberjs.
我在路线上有动态元素.如果我通过应用程序导航,一切都很好.问题是当我重新加载页面或键入 url 时.在这种情况下,应用程序输入反序列化函数并通过它们的 ID 加载和对象,但此加载是异步的.
I have dynamic element at routes. All is ok if I navigate throuht application. The problem is when I reload a page or when a type the url. In that case the app enter in the deserialize function and load and object by their id, but this load is asynchronous.
问题 #1268 lukemelia 说你需要让你的结果反序列化方法实现了承诺模式".
At issue #1268 lukemelia says "you will need to make the result of your deserialize method implement the promises pattern".
我尝试过,但总是松散的上下文.我的代码类似于:
I try it but always loose context. My code is similar to:
page: Ember.Route.extend
route: '/:alias'
deserialize: (router, params) -> page=App.Page.find(params.alias)
$.when( page.get("isLoaded") ).done( () -> console.debug(page.get("alias")) return page)
loading: Em.State.extend
路由器进入加载状态,但返回时没有上下文数据.我想我做错了什么.可能一切都错了.
The router goes to loading state but then return with no context data. I think i doing something wrong. Possibly all is wrong.
有人可以帮我吗?有没有例子?
Can anybody help me? Is there and example?
谢谢!
已解决:
page: Ember.Route.extend
route: '/:id'
deserialize: (router, params) ->
page=App.Page.find(params.id})
deferred = $.Deferred()
page.addObserver("isLoaded", -> deferred.resolve(page))
return deferred.promise()
serialize: (router, page) ->
return {id: page.get("id") }
connectOutlets: (router, page) ->
router.get('applicationController').connectOutlet
context: page
name: "page"
loading: Em.State.extend
connectOutlets: (router, context) ->
router.get('applicationController').connectOutlet(context: context, name: "loading")
页面加载时活动状态为loading,页面加载完成后,路由器自动加载页面状态.
While page is loading the active state is loading, when page finish loading, router load page state automatically.
我希望这可以帮助某人
推荐答案
@leroj7 您已经找到了一个可行的解决方案.感谢分享.我创建了一个 mixin,将其添加到需要具有此行为的模型中:
@leroj7 you've figured out a workable solution. Thanks for sharing it. I've created a mixin that I add to models that I need to have this behavior:
Editor.ModelPromise = {
init: function() {
this._super();
this._deferred = $.Deferred();
this._deferred.promise(this);
this.one('didLoad', this, '_resolveModelPromise');
this.one('becameError', this, '_rejectModelPromise');
},
_resolveModelPromise: function() {
this._deferred.resolve(this);
},
_rejectModelPromise: function() {
this._deferred.reject(this);
}
};
也可在 https://gist.github.com/1b54f0956ba10195a3bc
这样的方法最终会被嵌入到 ember-data 中,尽管它很可能不会依赖 jQuery,因为 ember-data 目前不依赖于 jQuery.
An approach like this will eventually be baked into ember-data, though it will most likely NOT have a jQuery dependence, since ember-data does not currently depend on jQuery.
这篇关于Emberjs 异步路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!