For most of last year I was a React developer at DigitalOcean, and I still observe what’s happening in the React world. One feature I have missed from React is the ability to define styles on your components using Javascript.

While of course you can do this in Ember by producing a string of styles and binding it to the style attribute, it can become complicated when you want to produce a style string from multiple computed properties, not to mention string interpolation just looks awful when skimming over code.

To solve this problem I’ve released a new add-on called ember-computed-style, which allows you to define styles as objects and have them bound as a style string computed from the keys and values, which is then escaped for safety in Handlebars.

Example:

Example component using computedStyle to bind the style attribute of this component

I’ll let the above code do all the talking.

When this component renders it will set the style attribute with the computed style string based on the backgroundStyle property.

<div style="background-color:red;" class="ember-view">...

Of course the property names will be dasherized, and the values will be interpreted correctly as to whether they should be unit-less or not. So you can specify margins and positioning as regular numbers and have them rendered in “px” units.

If you want to remove a property completely, just have it return null or some empty value. This is useful for display: none; toggles.