Skip to content

Instantly share code, notes, and snippets.

@mrozema
Last active August 2, 2016 03:37
Show Gist options
  • Save mrozema/4d0159b76eca610d7706 to your computer and use it in GitHub Desktop.
Save mrozema/4d0159b76eca610d7706 to your computer and use it in GitHub Desktop.
Ember 2.0 compatible select box
import Ember from "ember";
export default Ember.Helper.helper(function([content, group, contentGroupKey]) {
return content.filterBy(contentGroupKey, group);
});
import Ember from "ember";
export default Ember.Helper.helper(function([lhs, rhs]) {
return lhs === rhs;
});
import Ember from "ember";
export default Ember.Helper.helper(function([value]) {
return !value;
});
import Ember from "ember";
export default Ember.Helper.helper(function([object, path]) {
return Ember.get(object, path);
});
<select disabled={{disabled}} class="{{class}}" {{action 'change' on='change'}}>
{{#if prompt}}
<option disabled selected={{is-not selection}}>
{{prompt}}
</option>
{{/if}}
{{#if groups}}
{{#each groups as |group|}}
<optgroup label={{group.label}}>
{{#each (content-for-group content group.value optionGroupPath) as |item|}}
<option value={{read-path item optionValuePath}}
selected={{is-equal (read-path item optionValuePath) selection}}>
{{read-path item optionLabelPath}}
</option>
{{/each}}
</optgroup>
{{/each}}
{{else}}
{{#each content as |item|}}
<option value={{read-path item optionValuePath}}
selected={{is-equal (read-path item optionValuePath) selection}}>
{{read-path item optionLabelPath}}
</option>
{{/each}}
{{/if}}
</select>
import Ember from 'ember';
export default Ember.Component.extend({
content: [],
prompt: null,
optionValuePath: 'value',
optionLabelPath: 'label',
init: function () {
this._super(...arguments);
if (!this.get('content')) {
this.set('content', []);
}
},
actions: {
change: function () {
let selectedIndex = this.$('select')[0].selectedIndex;
let content = this.get('content');
// decrement index by 1 if we have a prompt
let hasPrompt = !!this.get('prompt');
let contentIndex = hasPrompt ? selectedIndex - 1 : selectedIndex;
let _selection = content[contentIndex];
this.sendAction('willChangeAction', _selection);
if (this.get('optionValuePath')) {
this.set('selection', _selection[this.get('optionValuePath')]);
} else {
this.set('selection', _selection);
}
this.sendAction('didChangeAction', _selection);
}
}
});
@srsgores
Copy link

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment