Ember Data Customization
This guide is updated for Ember Data version 1.0 beta 9.
To customize your data handling in Ember Data, you have the option to extend one of the Ember Data Adapters. If you want to apply changes site-wide, you can use the following code:
App.ApplicationAdapter = DS.RESTAdapter.extend(....
If you prefer to make changes specific to a model, you can use the following approach:
App.FooAdapter = DS.RESTAdapter.extend(...
You can define the implementation you wish to override by using methods like this._super
to fallback to the base implementation when needed. For example:
App.NotesAdapter = DS.RESTAdapter.extend({
find: function(store, type, id) {
id = "foo" + id;
return this._super(store, type, id);
}
});
If you want to completely overhaul the default behavior, you can override multiple methods as shown below:
App.NotesAdapter = DS.RESTAdapter.extend({
find: function(store, type, id) {
// Customize your logic here
return this.ajax(this.buildURL(type.typeKey, id), 'GET');
},
findAll: function(store, type, sinceToken) {
// More customization here
var query;
if (sinceToken) {
query = { since: sinceToken };
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
.....
});
For more detailed API documentation on customizing adapters, you can visit:
Data Serialization
In many cases, creating your own serializer is essential for adapting data to fit your REST endpoint properly. Refer to the transition document at https://github.com/emberjs/data/blob/master/TRANSITION.md for valuable insights.
The serialization process involves several hooks that allow you to manipulate the payload after an Ajax request completes. You can utilize methods like extractSingle, extractArray, and normalize for this purpose.
App.FooAdapter = Ember.Object.extend({
find: function(id){
return $.getJSON('http://www.foolandia.com/foooo/' + id);
}
});
You can then retrieve data using the adapter in your route or other components:
App.FooRoute = Ember.Route.extend({
model: function(){
var adapter = App.FooAdapter.create();
return adapter.find(1);
}
});
For convenience, consider injecting the adapter into routes:
App.initializer({
name: "fooAdapter",
initialize: function (container, application) {
application.register("my:manager", application.FooAdapter);
application.inject("controller", "fooAdapter", "my:manager");
application.inject("route", "fooAdapter", "my:manager");
}
});
Then you can access the adapter directly within the route:
App.FooRoute = Ember.Route.extend({
model: function(){
return this.fooAdapter.find(1);
}
});
See an example in action:
To explore using Ember without Ember Data, check out: Ember without Ember Data