Ember Data Mockjax
by alexspeller
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' id='posts'>
<h2>Posts by</h2>
<button {{action 'newPost'}}>New</button>
<button {{action 'newRunNext'}}>New (Run Next)</button>
<ul>
{{#each}}
<li>
{{title}} {{#if isNew}}(new record) {{/if}}
<ol>{{#each tags}}<li>{{name}}</li>{{/each}}</ol>
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars">
<div class="container">
<h1>Ember Data HasMany example</h1>
<p>This JSFiddle demonstrates that I cannot create a hasMany relationship on a new record.</p>
<div>{{render 'posts' model}}</div>
</div>
</script>
CSS
button {
font-size: 16px;
cursor: pointer;
}
.msg {
font-size: 12px;
color: red;
}
JavaScript
window.App = Em.Application.create();
App.ApplicationAdapter = DS.ActiveModelAdapter.extend();
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return this.store.find('post');
}
});
App.PostsController = Ember.ArrayController.extend({
actions: {
newPost: function() {
var post = this._newPost()
this._newTag(post);
},
// creates hasMany in the next run loop
// using Em.run.next
newRunNext: function() {
var self = this;
var post = self._newPost();
// create the tag in the next run loop
Em.run.next(this._newTag.bind(this, post));
}
},
_newPost: function() {
return this.store.createRecord('post', {
title: "Post #" + (this.get('length') + 1),
});
},
_newTag: function(post) {
post.get('tags').then(function(tags){
tags.createRecord({
name: 'fiction'
})
});
},
});
/* MODEL DEFINITIONS */
App.Post = DS.Model.extend({
title: DS.attr('string'),
tags: DS.hasMany('tag', {async: true})
});
App.Tag = DS.Model.extend({
name: DS.attr('string'),
post: DS.belongsTo('post', {async: true})
});
/* MOCKJAX REQUESTS */
$.mockjax({
url: "/posts",
responseText: {
posts: [
{ id: 1, title: "Post #1" },
{ id: 2, title: "Post #2" },
]
}
});