Ember Data Mockjax

by mehulkar

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.2/jquery.mockjax.js"></script>
<script src="http://ember.alexspeller.com/handlebars-1.0.0.js"></script>
<script src="http://ember.alexspeller.com/ember-latest.js"></script>
<script src="http://ember.alexspeller.com/ember-data-latest.js"></script>
<script type="text/x-handlebars">
    <h2> Deleting Records in Ember Data</h2>
    <p>
        When you rollback a deletion, notice that the parent is reassociated, but the parent doesn't have it's children back. i.e. on rollback, post.get('author') works, but author.get('posts') does not!
    </p>
    {{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
    <h3>Child</h3>
    <p>
        "{{title}}" by {{author.name}}. (isDeleted? {{isDeleted}})
    </p>

    <h3>Parent</h3>
    <p>{{author.name}} has {{author.posts.length}} posts:</p>
    <ol>
        {{#each author.posts}}
        <li>"{{title}}" by {{author.name}}</li>
        {{/each}}
    </ol>
    <h3>Test</h3>
    <p>Try deleting the "{{title}}" and then rolling back that deletion</p>
    <button {{action 'deleteRec' this}}>Delete</button>
    <button {{action 'discardChanges'}}>Rollback</button>
  </script>

JavaScript

window.App = Em.Application.create();
App.ApplicationAdapter = DS.ActiveModelAdapter.extend();
    
App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('post', 1);
  }
});


// The important part of this demo
App.IndexController = Ember.ObjectController.extend({
  init: function() {
    this.set('deletedRecords', Em.A());
  },
  
  actions: {
    deleteRec: function(record) {
      this.get('deletedRecords').pushObject(record);
      record.deleteRecord();
    },
    
    discardChanges: function() {
      this.get('deletedRecords').forEach(function(record){
        record.rollback();
      });
    }
  }
});

App.Post = DS.Model.extend({
    title: DS.attr('string'),
    author: DS.belongsTo('author')
});

App.Author = DS.Model.extend({
    name: DS.attr('string'),
    posts: DS.hasMany('post')
});

$.mockjax({
    url: "/posts/1",
    responseText: {
        post: {
            id: 1,
            title: "Cool post",
            author_id: 1
        }
    }
});

$.mockjax({
    url: "/authors/1",
    responseText: {
        author: {
            id: 1,
            name: "Tomsterhuda",
            post_ids: [1]
        },
    }
});