Hello Ember Data can be uncomfortable to work with at times. Some developers even see it as a lot of bloat. But, I would argue if you aren't using Ember Data, you are building Ember Data for yourself (and likely aren't as efficient).
What Do You Want From a Data Store
So when you grab data from a server, you are going to want a few things.
- An abstraction to say when to grab a collection (or index) of a single type of resource
- An abstraction for grabbing a single record from a resource
- An abstraction to save, reload, and delete existing records you have loaded
- An abstraction for saving a new record
What Do You Want From a Model
- A way to create computed properties
- A way to check the original state of the model from the server
- A way to quickly see if the record has been modified
This isn't incredibly hard to accomplish with jQuery and some of the classes in Ember Metal:
// models/post.js
export default Ember.Object.extend({
savedProperties: ['title', 'body'],
title: '',
body: '',
originalContent: {},
isNew: true,
isDirty: true,
store: null,
save: function() {
if (this.get('isNew')) {
return this.store.create(this);
} else {
return this.store.update(this);
}
},
getAttributes: function() {
return this.getProperties(this.get('savedProperties'));
}
});
// store/post.js
import Post from 'app/models/post';
export default function() {
var Model = Post;
var url = '/api/posts';
var singularKey = 'post';
var pluralKey = 'posts';
this.create = function(post) {
return $.ajax({
method: 'POST',
data: JSON.stringify(post.getAttributes()),
contentType : 'application/json',
dataType: "json",
url: url,
success: function(result) {
return Model.create(result[singularKey]);
}
});
};
this.all = function() {
return $.ajax({
method: 'GET',
contentType : 'application/json',
dataType: "json",
url: url,
success: function(result) {
return ArrayProxy.create({content: result[pluralKey]})
.map(function(record) {
return Model.create(record);
});
}
});
};
// And on and on
}
This works ok but there are some pain points that you would still have to consider.
- Instantiating more than one store
- Changing the namespace of the API
- Query params for search
And there are probably things you didn't realize that you wanted or didn't want to think about implementing:
- Don't grab a record if you already have it in the store
- Make reusable for many other types of records
- Managing promise state and data
- Handling error states
Ember Data gives you all of this and more in a simple abstraction. But, while providing a simple API for you to use, Ember Data is heavily customizable by modifying various methods on the model and by creating Serializers and Adapters.
To learn more about using and modifying Ember Data, sign up for the mailing list at EmberGrep and I will keep you up to date on the progess of the "Ember and APIs" and "Customizing Ember Data" screencast courses that I am working on.