Skip to content

Instantly share code, notes, and snippets.

@jarredkenny
Created July 30, 2015 13:36
Show Gist options
  • Save jarredkenny/d0a7c22c2023f2a70f61 to your computer and use it in GitHub Desktop.
Save jarredkenny/d0a7c22c2023f2a70f61 to your computer and use it in GitHub Desktop.
ui-select component. Replacement for the Ember.Select view with Semantic UI integration.
import Ember from 'ember';
export default Ember.Component.extend({
/**
* Component Configuration
*/
tagName: 'div',
classNames: ['ui', 'dropdown', 'selection'],
classNameBindings: ['search', 'fluid'],
/**
* Component Attributes
*/
content: null,
value: null,
optionValuePath: null,
optionLabelPath: null,
/**
* Component Setup
*/
setup: Ember.on('didInsertElement', function(){
this.$().dropdown();
}),
/**
* Content Observer
* Fires on init and anytime the underlying content array changes.
* Watches the content array and parses it into an internal selection
* structure that allows for both arrays of objects and strings to be
* supported.
*/
contentObserver: Ember.on('init', Ember.observer('content.[]', function(){
let i = 0;
let options = [];
let value = this.get('value');
let content = this.get('content');
let ovp = this.get('optionValuePath');
let olp = this.get('optionLabelPath');
if(content === null) {return;}
content.forEach((item) => {
if(typeof item === 'string'){
options.pushObject(
{
id: i++,
title: item,
value: item
});
}
else if(typeof item === 'object'){
if(ovp !== null){
options.pushObject({
id: i++,
title: item.get(olp),
value: item.get(ovp)
});
}else{
options.pushObject({
id: i++,
title: item.get(olp),
value: item
});
}
}
});
this.set('options', options);
// If a default value is bound, select it.
if(value !== null){
options.filter((option) => {
if(option.value === value){
this.set('selectedId', "%@".fmt(option.id));
}
});
}
})),
/**
* selectedId observer
* Watches the selected option ID, finds the associated option
* in the options array and updates the components value binding
* to that option.
*/
selectedIdObserver: Ember.observer('selectedId', function(){
let options = this.get('options');
let selectedId = this.get('selectedId');
if(options === null) {return;}
let selection = options.filter((option) => {
return "%@".fmt(option.id) === selectedId;
}).get('firstObject');
this.set('value', selection.value);
})
});
{{input type="hidden" value=selectedId}}
<i class="dropdown icon"></i>
<div class="default text">{{placeholder}}</div>
<div class="menu">
{{#each options as |option|}}
<div class='item' data-value={{option.id}}>{{option.title}}</div>
{{/each}}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment