Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs async routing

Tags:

ember.js

My problem is related with the issues #1183 and #1268 of emberjs.

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.

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?

Thanks!

Resolved:

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")

While page is loading the active state is loading, when page finish loading, router load page state automatically.

I hope this may help somebody

like image 388
leroj7 Avatar asked Aug 20 '12 08:08

leroj7


1 Answers

@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);
  }
};

Also available at https://gist.github.com/1b54f0956ba10195a3bc

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.

like image 72
Luke Melia Avatar answered Nov 11 '22 21:11

Luke Melia