lundi 7 septembre 2020

EmberJS: Dynamic properties for Ember data model (native class)

I'm working on migrating from EmberObject to native classes (using Ember 3.16), but I've got an issue. Basically, I need to set dynamic properties to some models. These properties are defined elsewhere, but for simplicity sake, I'm going to define them in the component files in the following examples.

Here are my EmberObject model and native class model:

// EmberObject
import Model from 'ember-data/model';
import attr from 'ember-data/attr';

function getAttrs(config) {
  return Object.keys(config).reduce((reduced, key) => {
    const transform = config[key].type === 'text' ? 'string' : '';
    reduced[key] = attr(transform);
    return reduced;
  }, {});
}

const dynamicProps = { location: { name: 'Location', type: 'text', defaultValue: '' } };

export default Model.extend(assign({
  comment: attr('string'),

}, dynamicProps));

//Native class
import Model, { attr } from '@ember-data/model';
import { assign } from '@ember/polyfills';

function getAttrs(config) {
  return Object.keys(config).reduce((reduced, key) => {
    const transform = config[key].type === 'text' ? 'string' : '';
    reduced[key] = attr(transform);
    return reduced;
  }, {});
}

const dynamicProps = { location: { name: 'Location', type: 'text', defaultValue: '' } };

export default class SomeModel extends Model {
  @attr('string') comment

  constructor() {
    super(...arguments);
    assign(this, dynamicProps);
  }
}

As you can see, what I want is for the native class to have a @attr('string') location in this example, but this isn't working for me.




Aucun commentaire:

Enregistrer un commentaire