I am an ember beginner and created a test without Ember Data for the WordPress JetPack json API: http://broerse.net/ember/wp3/#/posts (resulting in one JetPack call)
If you access a post via an URL like http://broerse.net/ember/wp3/#/posts/3787 I don’t know how to return a post with an ‘id’ from the objects created with findAll. I ended up fetching the specific post by ‘id’ from JetPack again. Is there a way to rewrite ‘find’ in the code below so there is no need for two JetPack call’s?
App = Ember.Application.create();
App.Router.map(function() {
this.resource('posts', function() {
this.resource('post', { path: ':post_id' });
});
});
App.Post = Ember.Object.extend();
App.Post.reopenClass({
findAll: function() {
return Ember.$.ajax({ url: 'http://public-api.wordpress.com/rest/v1/sites/58826716/posts/?number=10', dataType: "jsonp", type: 'GET' }).then(function(data) {
return data.posts.map(function(post) {
post['id'] = post['ID'];
delete post['ID'];
return App.Post.create(post);
});
});
},
find: function(id) {
return Ember.$.ajax({ url: 'http://public-api.wordpress.com/rest/v1/sites/58826716/posts/' + id + '/', dataType: "jsonp", type: 'GET' }).then(function(post) {
post['id'] = post['ID'];
delete post['ID'];
return App.Post.create(post);
});
}
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return App.Post.findAll();
}
});
App.PostRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
}
});
The PostRoute
can be modified to look for the post in the model already loaded by the PostsRoute
. If found will return it, otherwise will try to loaded it through the ajax call.
App.PostRoute = Ember.Route.extend({
model: function(params) {
var post = this.modelFor("posts").findBy("id",parseInt(params.post_id));
if(Em.isEmpty(post)){
return App.Post.find(params.post_id);
}else{
return post;
}
}
});