Created
February 13, 2019 10:59
-
-
Save glen-84/4da345dfb99f7553bf9c33312003b630 to your computer and use it in GitHub Desktop.
Number array custom attribute
This file contains hidden or 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 {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