mardi 27 septembre 2016

Spreading plain objects into Ember Component

I'm working with Ember (ember-cli v2.8.0) and trying to add some properties to a component. I found a few objects were using really similar code, so I created a function to generate the code rather than copy&pasting all over. In my ember-cli-build.js I've added the following babel options:

var app = new EmberApp(defaults, {
  babel: {
    optional: ['es7.decorators']
  },
  /* ... */
});

This is a simplified version of the generator function:

function generateProperties(name, defaultValue) {
  return {
    [name]: defaultValue,
    [`tenTimes${name.capitalize()}`]: 10 * defaultValue
  };
}

If I test out the object spread notation it looks fine in the console:

console.log(generateProperties('five', 5));
console.log({ ...generateProperties('five', 5) });

/* Both output { five: 5, tenTimesFive: 50 } */

Now I want to use that in an Ember component:

Ember.Component.extend({
  four: 4,
  ...generateProperties('five', 5),
  ...generateProperties('six', 6),
  seven: 7
});

Now I get a syntax error - the code that gets generated looks like this:

_ember['default'].Component.extend({
  { key: 'four', initializer: function initializer() { return 4; } },
  { key: },
  { key: },
  { key: 'seven', initializer: function initializer() { return 7; } },      
});

What's going on here?? The workaround I came up with is this:

Ember.Component.extend(generateProperties('five', 5), { four: 4 })

It seems to work, but all the documentation I can find says that you can use as many Mixins as you want, and then the object properties. These aren't technically Mixins, so it seems like it might bite me later on. Is this a proper workaround? Why doesn't the object spread notation work here?




Aucun commentaire:

Enregistrer un commentaire