Skip to content

Instantly share code, notes, and snippets.

@dfreeman
Last active June 15, 2016 14:53
Show Gist options
  • Save dfreeman/b223f015c9e6e861ceb54e5dbee60c70 to your computer and use it in GitHub Desktop.
Save dfreeman/b223f015c9e6e861ceb54e5dbee60c70 to your computer and use it in GitHub Desktop.
Local Classes
import Ember from 'ember';
const { dasherize } = Ember.String;
// Imagine this is automagically mixed into all components
const LocalClassesMixin = Ember.Mixin.create({
localClassNames: null,
localClassNameBindings: null,
concatenatedProperties: ['localClassNames', 'localClassNameBindings'],
init() {
this._super();
this.classNameBindings = this.classNameBindings.concat([
...this.localClassNames.map(className => `styles.${className}`),
...this.localClassNameBindings.map((classNameBinding) => {
const [property, trueClass = dasherize(property), falseClass] = classNameBinding.split(':');
const binding = [property, this.get(`styles.${trueClass}`)];
if (falseClass) {
binding.push(this.get(`styles.${falseClass}`));
}
return binding.join(':');
})
]);
}
});
// Pretend this came from a compiled `styles.css`
const styles = {
'a': '_a_abc123',
'b': '_b_def456',
'c': '_c_ghi789',
'd': '_d_jkl012',
'e': '_e_mno345'
};
// Actual component for this file
export default Ember.Component.extend(LocalClassesMixin, {
styles,
classNames: 'a',
classNameBindings: ['b', 'isC:c', 'isD:d:e'],
localClassNames: 'a',
localClassNameBindings: ['b', 'isC:c', 'isD:d:e'],
b: false,
isC: false,
isD: false
});
body {
margin: 12px 16px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12pt;
}
label {
display: block;
}
.a::before {
display: block;
content: "classes: " attr(class);
border: 1px solid #999;
font-family: monospace;
font-size: 0.8em;
padding: 3px;
margin-bottom: 5px;
}
<label><input type="checkbox" checked={{b}} onchange={{action (mut b) value='target.checked'}}> b</label>
<label><input type="checkbox" checked={{isC}} onchange={{action (mut isC) value='target.checked'}}> isC</label>
<label><input type="checkbox" checked={{isD}} onchange={{action (mut isD) value='target.checked'}}> isD</label>
{
"version": "0.8.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.5.1",
"ember-data": "2.5.2",
"ember-template-compiler": "2.5.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment