问题
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