Created
July 30, 2015 13:36
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment