Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@glen-84
Created February 13, 2019 10:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glen-84/4da345dfb99f7553bf9c33312003b630 to your computer and use it in GitHub Desktop.
Save glen-84/4da345dfb99f7553bf9c33312003b630 to your computer and use it in GitHub Desktop.
Number array custom attribute
import {autoinject, bindingMode, customAttribute} from "aurelia-framework";
/**
* Ensures that array elements are numbers.
*
* TODO: Using this custom attribute because value converters and binding behaviors are not working well with
* multi-select elements. See https://github.com/aurelia/binding/issues/611.
*/
@autoinject
@customAttribute("gg-number-array", bindingMode.twoWay)
export class GgNumberArrayCustomAttribute {
public value;
private readonly element: HTMLSelectElement;
public constructor(element: Element) {
this.element = (element as HTMLSelectElement);
}
public valueChanged() {
Array.from(this.element.options).map((option) => {
const optionValue = (option["model"] || option.value);
if (this.value.indexOf(parseInt(optionValue, 10)) === -1) {
option.selected = false;
} else {
option.selected = true;
}
});
}
public bind() {
this.element.addEventListener("change", this.change);
}
public unbind() {
this.element.removeEventListener("change", this.change);
}
public attached() {
this.valueChanged();
}
public change = () => {
this.value = Array.from(this.element.selectedOptions).map((selectedOption) => {
const selectedOptionValue = (selectedOption["model"] || selectedOption.value);
if (typeof selectedOptionValue === "string") {
const intValue = parseInt(selectedOptionValue, 10);
if (isNaN(intValue)) {
return selectedOptionValue;
}
return intValue;
}
return selectedOptionValue;
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment