Deserialize with an async callback

こ雲淡風輕ζ 提交于 2020-01-13 06:01:13

问题


I'm overriding the deserialize method so I can load an object from the backend corresponding with the id. However, the way I get this object is asynchronous. Deserialize does not wait for my callback and returns automatically.

Example:

show: Em.Route.extend({
        route: "/:id",
        deserialize: function(router, post) {
            var postController = router.get('postController ');
            postController.findById(post.id, function(post) {
                return post
            });
        }

The call to the backend is made but deserialize returns automatically. Is there a way to work with asynchronous call in deserialize?

Thank you


回答1:


Luke Melia did an NYC Ember meetup lightning talk on this very thing, using Promises via jQuery Deferred objects. Basically, Ember detects if you return a Promise (by seeing if the object has a then method), and puts the route in a loading state (which you have to declare as a sibling of the state with the deserialize). On ajax.done, you can resolve the promise, which puts the router fully in the state with the data fully loaded.

With the new router, you're not really supposed to use the support for async transitions that is present in the vanilla statemanager, but you can use the automatic loading states to achieve the same kind of thing.




回答2:


Here is what i have found out, this would work in older versions of ember:

In the enter function of the state/route you can try to load the data. The enter function receives as second argument at transition object which have 2 methods. One is 'async' which tells the transition that it cant continue until the other method 'resume' has bean called.

So in the example:

    ...
    enter: function (r, t) {
           t.async();
           r.get('postController').loadResources(t.resume);
    },
    ...



回答3:


For newer versions of Ember you should use some kind of proxy for the data you load.

    {
      PostController: Ember.ObjectController.extend({
          find: function (id) {
              var ajax = Em.$.ajax(); //call the ajax thing
              ajax.done(Em.$.proxy(function (data) {
                  this.set('content', data);
              }, this));
              return this;
          }
      })
      ...
      Router: Em.Router.extend({
          show: Em.Route.extend({
              deserialize: function(router, post) {
                  var postController = router.get('postController');
                  postController.find(post.id);
                  return postController;
              }
          });
      })
    }


来源:https://stackoverflow.com/questions/11244938/deserialize-with-an-async-callback

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!