Problem

You want to load data from a server and have it available in your Ember application for observation and manipulation.

Solution

Use jQuery.ajax and convert the response into Ember observable objects. You use reopen to add a finder method to your model class. The general workflow of the finder method is the following:

  1. You create an empty result object.
  2. You make an asynchronous call to your API…
  3. … and in your success callback you fill your empty object.
  4. You return your result object.

Note the slight differences between returning an array and a single object.

  1. App.User.reopenClass({
  2. findAll : function(){
  3. var result = [];
  4. $.ajax({
  5. url : '/users',
  6. dataType : 'json',
  7. success : function(response) {
  8. response.forEach(function(user){
  9. var model = App.User.create(user);
  10. result.addObject(model);
  11. });
  12. }
  13. });
  14. return result;
  15. },
  16. findById : function(id){
  17. var result = App.User.create();
  18. $.ajax({
  19. url : '/users/' + id,
  20. dataType : 'json',
  21. success : function(response) {
  22. result.setProperties(response);
  23. }
  24. });
  25. return result;
  26. }
  27. });

Discussion

Alternatively you could also return a promise (Ember.Deferred) with your finder methods. The code for this approach could look like the following:

  1. App.User.reopenClass({
  2. findAll : function(){
  3. var promise = Ember.Deferred.create();
  4. $.ajax({
  5. url : '/users',
  6. dataType : 'json',
  7. success : function(response) {
  8. var result = [];
  9. response.forEach(function(user){
  10. var model = App.User.create(user);
  11. result.addObject(model);
  12. });
  13. promise.resolve(result);
  14. }
  15. });
  16. return promise;
  17. },
  18. findById : function(id){
  19. var promise = Ember.Deferred.create();
  20. $.ajax({
  21. url : '/users/' + id,
  22. dataType : 'json',
  23. success : function(response) {
  24. var result = App.User.create();
  25. result.setProperties(response);
  26. promise.resolve(result);
  27. }
  28. });
  29. return promise;
  30. }
  31. });

Example

JS Bin