ember.js and the server

writes_on picture writes_on · Jan 20, 2012 · Viewed 22.2k times · Source

I'm looking at Ember.js and have been reading the docs to try and understand how to use it. I get it (pretty well), except for one thing. To my way of thinking in the MVC pattern, the Model is the repository for data in the application. I can see how that works for client side data in Ember.js. What I don't get is how to tie that data back to the server so that if data changes at the client, the changes are updated in server. And vice versa. I've been doing this by in in my web applications making Ajax/JSON calls to back and forth to the server, I'm just not getting how to do that using Ember.js.

Answer

Misha Reyzlin picture Misha Reyzlin · Jan 20, 2012

Digging just a bit around emberjs on GitHub I have found this: https://github.com/emberjs/data:

Ember Data is a library for loading models from a persistence layer (such as a JSON API), updating those models, then saving the changes. It provides many of the facilities you'd find in server-side ORMs like ActiveRecord, but is designed specifically for the unique environment of JavaScript in the browser.

I'd also suggest reading Ember.js Live Collections. What you want is to have a collection of models that will know how to sync with server side, possible example code is:

// our model
App.Person = Ember.Object.extend();

App.people = Ember.ArrayController.create({
  content: [],
  save: function () {
    // assuming you are using jQuery, but could be other AJAX/DOM framework
    $.post({
      url: "/people",
      data: JSON.stringify( this.toArray() ),
      success: function ( data ) {
        // your data should already be rendered with latest changes
        // however, you might want to change status from something to "saved" etc.
      }
    });
  }
});

You'd then call App.people.save() at needed occasions.

Also be sure to check out this article, Advice on & Instruction in the Use Of Ember.js, that goes deeper into server-client communication with Ember and also mentions emberjs/data.

Note: Emberjs Data Library should be used with caution for the fact that it is not production ready.