The Basic Adapter

The most basic way to use Ember Data is to make your own Ajax requests using jQuery’s Ajax helpers and process the data yourself before loading it into your records.

The basic adapter allows you to implement hooks to talk to your backend, then load the data returned into the store.

You provide the hooks to Ember Data by implementing a sync object on each model:

  1. App.Person = DS.Model.extend({
  2. //...model definition...
  3. });
  4. App.Person.sync = {
  5. find: function(id, process) {
  6. // ...
  7. }
  8. };

Finding Records

When you use the find method on a model in your application, Ember Data will invoke the find hook on your model’s sync object.

  1. App.Person.find(1);
  2. App.Person.sync = {
  3. find: function(id, process) {
  4. jQuery.getJSON("/people/" + id).then(function(json) {
  5. process(json).camelizeKeys().load();
  6. });
  7. }
  8. }

This will load the JSON representation returned from the server for the Person with the given id.

The process function passed into find wraps a JavaScript object and provides conveniences for normalizing it. Once you are done working with the JSON, you call load to load the normalized data into the record.

Ember Data expects that the JSON you load in will have keys with the same name as the attributes and relationships that you have defined in the model. For example, if you have a Person model:

  1. App.Person = DS.Model.extend({
  2. firstName: DS.attr('string'),
  3. lastName: DS.attr('string'),
  4. age: DS.attr('number')
  5. });

You need to load an object that looks like this:

  1. {
  2. firstName: "Peter",
  3. lastName: "Wagenet",
  4. age: 25
  5. }

Because underscored keys are so common, the process wrapper provides the camelizeKeys method to convert all keys from underscored keys to camelized keys.

For other kinds of manipulations, the process wrapper provides a munge method you can use to change the JSON object:

  1. App.Person.sync = {
  2. find: function(id, process) {
  3. jQuery.getJSON("/people/" + id).then(function(json) {
  4. process(json)
  5. .munge(function(json) {
  6. json.firstName = json.FIRST_NAME;
  7. json.lastName = json["name,last"];
  8. })
  9. .load();
  10. });
  11. }
  12. }

You can modify the JSON before passing it to process. The munge API is provided to make it easier to compose with other methods on the process wrapper.

Querying for Multiple Records

When you use the query method on a model, Ember Data will invoke the query hook on your model’s sync object.

  1. App.Person.query({ page: 1 });
  2. App.Person.sync = {
  3. query: function(query, process) {
  4. jQuery.getJSON("/people", query).then(function(json) {
  5. process(json).camelizeKeys().load();
  6. });
  7. }
  8. }

In the case of a query, the process wrapper will wrap an Array of returned objects.