Ember initializing route model with query

倾然丶 夕夏残阳落幕 提交于 2020-01-21 12:18:22

问题


I am trying to initialize a Route's model with a DS query, as follows

App.Router.map(function() {
    this.resource('post', { path: '/posts/:post_slug' });
});

App.PostsRoute = Ember.Route.extend({
    model: function(params) {
        var records = App.Post.find({ slug: params.post_slug });
        return records.get('firstObject');
    }
});

Here, i find a Post by its slug and set the first result as the route model. but since records is populated asynchronously, the model data is not set properly. What is the correct way to do this?


回答1:


Solved this with Deferred pattern.

App.PostsRoute = Ember.Route.extend({
    model: function(params) {
        var records = App.Post.find({ slug: params.post_slug });
        var promise = Ember.Deferred.create();
        records.addObserver('isLoaded', function() {
            promise.resolve(records.get('firstObject'));
        });
        return promise;
    }
});



回答2:


That should do that trick:

App.Router.map(function() {
  this.resource('posts');
  this.resource('post', { path: '/posts/:post_id' });
});

App.PostsRoute = Ember.Route.extend({
  model: function() {
    return App.Post.find();
  }
});

App.PostRoute = Ember.Route.extend({
  model: function(params) {
    return App.Post.find(params.post_id);
  }
});


来源:https://stackoverflow.com/questions/14924558/ember-initializing-route-model-with-query

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