Question

Is there any working and current example on how to use Zendesk's ember-resource adapter with ember.js? I think I understand how to define the models, but I can't find any hint on how to use it in controllers and routes.

Was it helpful?

Solution

In general, there are two approaches for a given route: (1) go immediately to the page and fill in data as it becomes available (2) wait for the data to be fetched before transitioning.

Case 1 is quite straightforward. You create an instance of the model class, call fetch, and return it.

var FooRoute = Em.Route.extend({
  model: function(params) {
    var foo = Foo.create({ id: params.id });
    foo.fetch();
    return foo;
  },

  setup: function(foo) {
    // foo is a Foo, but may not have its data populated
  }
});

Case 2 is more complicated because Ember-Resource's fetch method returns a promise that resolves with two arguments -- the underlying JSON data and the model itself. An Ember.Route that returns such a promise will only pass the first to setup, so we have to create our own promise:

var FooRoute = Em.Route.extend({
  model: function(params) {
    var foo = Foo.create({ id: params.id }),
        deferred = $.Deferred();
    foo.fetch().then(
      function(json, model) { deferred.resolve(model); },
      function(error) { deferred.reject(error); }
    );
    return deferred.promise();
  },

  setup: function(foo) {
    // foo is a Foo with its data populated
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top