3
votes

The site I'm building uses multiple Ember apps to manage different areas of the site. It used to be easy to share models definitions between apps. One app would define the models (i.e. App1.Product) and the other app (App2) could create them by calling createRecord on the model itself: App1.Product.createRecord({})

However, with Ember Data 1.0, all records are created off the store object. So this no longer works from App2:

App1.Product = DS.Model.extend({
    name: DS.attr('string'),
    price: DS.attr('number')
});

App2.IndexRoute = Ember.Route.extend({
  setupController: function(controller, products) {
      controller.set('products', [

          // DOESN'T WORK
          this.store.createRecord('product', {name: 'Robot', price: 10.55}),
          this.store.createRecord('product', {name: 'Blocks', price: 4.99})

      ]);
  }
});

This doesn't work since App2 doesn't have any Product model definitions defined on its namespace.

How can I share model definitions (and serializers and adapters) between apps now? The current hack I am doing is having a JS file that 'imports' all the shared models:

App2.Product = App1.Product;

But this gets tedious for a long list of models and adapters.

Is there a way to create a shell Ember application that the other apps inherit from? (instances of Ember.Application do not have an extend method).

2

2 Answers

3
votes

I would look into using a module loader like requirejs. If you aren't interested in that, build your own. Here's a simple example.

Models = {
  registerModels:function(app){
    var models = Object.keys(this),
        modelName,
        model;

    for(var i = 0; i< models.length;i++){
      modelName = models[i];
      model= this[modelName];

      if (this.hasOwnProperty(modelName) && modelName != 'registerModels'){
         app[modelName] = model;
      }
    }
  }
};

Models.Product = DS.Model.extend({
    name: DS.attr('string'),
    price: DS.attr('number')
});

Models.Color = DS.Model.extend({
    color: DS.attr()
});

Models.registerModels(App);

http://emberjs.jsbin.com/OxIDiVU/120/edit

0
votes

I'm using symlinks for this. For what it is, this solution works surprisingly well.

Here's the setup: we have a user-facing Ember app, and an admin-only app. They're in the same repo, under ember/ and admin/, respectively.

Instead of being a directory, admin/app/models looks like:

models -> ../../ember/app/models/

These links are extremely cheap to set up. Just run:

ln -s -r path-to-link-destination

Everything behaves as you'd expect-- and all edits happen under ember/app/models. I haven't run into any issues within my use case. You can also use the same technique to link specific Components, or other files you want to share between the apps.

As for disadvantages-- changing a file under a symlink doesn't seem to trigger a rebuild in ember-cli, and this solution probably won't work on Windows.