ember.jsember-model

How to set an API url for Ember Model


I'm using Ember Model and I would like to set up a URL prefix for all my models, instead of prepending them on each model like this:

App.MyModel = Ember.Model.extend({
  id: attr(),
  myAttr: attr()
});

App.MyModel.reopenClass({
  url: ajaxUrl + '/some/obscure/path'
});

I'm aware I could probably override Ember.Model so that url defaults to ajaxUrl, but then if I want to set it to something other than default, like in the example above, I would have to prepend it.

If this is not possible, is there a recommended way to set a default url?


Solution

  • The best solution I came up with is to extend Ember.RESTAdapter itself.

    Ember.RESTAdapter = Ember.RESTAdapter.extend({
      ajaxSettings: function(url, method) {
        return {
          url: ajaxUrl + url,
          type: method
        };
      }
    });
    
    App.MyModel = Ember.Model.extend({
      id: attr(),
      myAttr: attr()
    });
    
    App.MyModel.reopenClass({
      adapter: Ember.RESTAdapter.create(),
      url: '/some/obscure/path'
    });
    

    Because that's the adapter I use for my models. I guess it's not ideal, but it works ok.