How to use ember-data with mixin?

Hello, suppose I am making a RPG, and a character can use an ablilty. My server api is rails, having a Ability class, and including 2 modules, Targetable and Attackable.

Base on the setting on rails, I have a model file in Ember:

import DS from 'ember-data';
export default DS.Model.extend({
  name : DS.attr('string'),
  cost : DS.attr('number'),
});

After that I have 2 mixins for this ablilty class:

import Ember from 'ember';

export default Ember.Mixin.create({
  targetable: DS.attr('boolean'),
});


import Ember from 'ember';

export default Ember.Mixin.create({
  attackable: DS.attr('boolean'),
  damage: DS.attr('number'),
  damageType: DS.attr('string'),
});

However when I get an ablilty from server, ember-data does not know which Mixin to include. My thought is that I can do it in serializer normalize function, but I am not 100% sure.

How to let ability serializer to know which mixin to include? Thank you.

BTW how to highlight my example in JS style?

I think the easiest solution for this is to just include all these properties in the model:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  cost: DS.attr('number'),
  targetable: DS.attr('boolean'),
  attackable: DS.attr('boolean'),
  damage: DS.attr('number'),
  damageType: DS.attr('string')
});

The non-available fields will simply be empty, so you can do

if (model.get('targetable') { 
  // do something
}

if (model.get('attackable') {
  // do something
}

to check the model.

Alternatively, you could also use a polymorphic model. But that would be a bit more complex, and maybe this easier solution is good enough for your use case.

PS: You can get nice syntax highlighting by doing:

```js // your code goes here ```

Yeah that is the way I do it now… I get a very fat model files with many attributes. I hope someday ED will support single table inheritance, just like in rails.

Hi,

You can extend a model as well.

Adding fields in mixin is not bad idea. But, If you have some fields common more than one field.

Just create a model that will be ‘parent’ model and then, other child model can extend it.

Like as below

**//parent-prod**
import DS from 'ember-data';
import Ember from 'ember';

export default DS.Model.extend({
    producttag1 : DS.attr('string'),
    producttag2 : DS.attr('string')
});


**//child-prod**

import parentModel from 'models/parent-prod';
import DS from 'ember-data';
import Ember from 'ember';

export default parentModel.extend({
    producttag3 : DS.attr('string'),
    producttag4 : DS.attr('string')
});


**//child1-prod**

import parentModel from 'models/parent-prod';
import DS from 'ember-data';
import Ember from 'ember';

export default parentModel.extend({
    producttag5 : DS.attr('string'),
    producttag6 : DS.attr('string')
});

Also note, that (at least when using JSONAPI, not sure how exactly that works with other adapters) you can use “real” polymorphic models, too: