Skip to content

Instantly share code, notes, and snippets.

@maletor
Forked from mrozema/content-for-group.js
Created May 3, 2016 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maletor/1d4dff369e40a13e246b51473ad36901 to your computer and use it in GitHub Desktop.
Save maletor/1d4dff369e40a13e246b51473ad36901 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);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment