2

This may seem like a simple question, but how can I use an external URL with Ember-model? All of the examples just assume the same domain. I would like to use e.g. apiary or firebase.

https://github.com/ebryn/ember-model

Cameron A. Ellis
  • 3,833
  • 8
  • 38
  • 46

1 Answers1

4

You can just set the full url as the property that gets set for the model instead of a relative URL. Like this:

App.User = Ember.Model.extend({
  id: attr(),
  name: attr(),
  comments: hasMany("App.Comment", {key: 'comment_ids'})
});

App.User.url = "http://example.com/users";

Update:

If you don't want to specify the hostname in multiple places, the simplest thing to do would probably be to assign the hostname to a variable and then reference the variable when you're declaring the URL. If you really want to get into the ember model internals, though, you could also override the buildURL method in a custom adapter, like this:

App.CustomAdapter = Ember.RESTAdapter.extend({
  buildURL: function(klass, id) {
    var urlRoot = "http://example.com/" + Ember.get(klass, 'url');
    if (!urlRoot) { throw new Error('Ember.RESTAdapter requires a `url` property to be specified'); }

    if (!Ember.isEmpty(id)) {
      return urlRoot + "/" + id + ".json";
    } else {
      return urlRoot + ".json";
    }
  }
});
Cameron A. Ellis
  • 3,833
  • 8
  • 38
  • 46
Adam
  • 3,148
  • 19
  • 20
  • Do I have to set this for every model type though? I was looking for more of a singleton solution. Thanks. – Cameron A. Ellis Feb 01 '14 at 05:32
  • 1
    The best thing I could think to do in a global sense is to assign the hostname to a variable and then reference that variable when you're setting up the URL per model. Also, you can create a custom adapter and override buildURL (feels somewhat dirty though). I know ember data provides the ability to specify the host name on a per model basis in a more reusable way. Unfortunately, that capability doesn't exist in ember model right now, as far as I can tell. Anyway, I'll update the answer to show what overriding the method would look like. – Adam Feb 01 '14 at 06:07