Ember WordPress test 4

If you access a post via an URL like http://broerse.net/ember/wp3/#/posts/3787 I didn’t know how to return the post with an ‘id’ from the objects created with findAll. I ended up fetching the specific post by ‘id’ from JetPack again. With much help from ‘melc’ and StackOverflow I changed my test to this:

http://broerse.net/ember/wp4/#/posts/3787

You can download the source from http://broerse.net/ember/wp4/wp4.zip or download the Ember Starter kit from http://emberjs.com/ and replace index.html and app.js files.

app.js

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

Comments

Comments are closed.