Hi,
I just extended the PowerSelect so I can set and get the selected values by only passing an identifying property of the options objects.
Maybe you wanna include that as a standard feature to the power select.
Here is the code:
import PowerSelect from 'ember-power-select/components/power-select';
import Ember from 'ember';
import { isEmberArray } from 'ember-array/utils';
export default PowerSelect.extend({
valueProperty:null,
actions: {
select(selected /*, e */) {
if (this.publicAPI.selected !== selected) {
let valueProperty = this.get("valueProperty");
if(valueProperty){
if(isEmberArray(selected)){
for(let i = 0; i < selected.length; i++){
if(Ember.typeOf(selected[i]) === 'object'){
selected[i] = selected[i][valueProperty];
}
}
} else if(Ember.typeOf(selected) === 'object'){
selected = selected[valueProperty];
}
}
this._super(selected);
}
},
},
updateSelection(selection) {
let valueProperty = this.get("valueProperty");
let options = this.get("options");
if(valueProperty && options && Ember.typeOf(options[0]) === 'object') {
if (isEmberArray) {
for (let i = 0; i < selection.length; i++) {
if (Ember.typeOf(selection[i]) !== 'object') {
selection[i] = options.findBy(valueProperty, selection[i]);
}
}
} else if (Ember.typeOf(selection) !== 'object') {
selection = options.findBy(valueProperty, selection);
}
}
this._super(selection);
},
});
If you like the idea I can build a pull request for this.
Can you put en example of how you use that from the template to be sure I get your intention?
js
export default Ember.Component.extend({
options:[
{label:"one", value:1}
{label:"two", value:2}
{label:"three", value:3}
],
selected:2
});
hbs
{{#power-select options=options valueProperty="value" selected=selected onchange=(action (muts elected)) as |option|}}
{{option.label}}
{{/power-select}}
as you see options is an array of objects, but selected will be the identifying value only
What I do and encourage other people to do is to use value="whatever" to extract that, in combination with the find-by helper:
{{#power-select options=options selected=(find-by 'id' id options) onchange=(action (mut id) value="id") as |option|}}
{{option.label}}
{{/power-select}}
Were you aware of this? I just a little bit more verbose but also has very little magic.
Yep, excactly. That's what I was looking for.
How do you so this with multi selects?
Maybe there is a way of doing that using map-by, filter-by and pipe, but I admit that I haven't done it.
I'm closing since I prefer users to do this themselves and keep the component simple. Thanks for the feedback.
Most helpful comment
What I do and encourage other people to do is to use
value="whatever"to extract that, in combination with the find-by helper:Were you aware of this? I just a little bit more verbose but also has very little magic.