All files / src/components boolean-attr-binding-behavior.ts

50% Statements 11/22
0% Branches 0/12
25% Functions 2/8
45% Lines 9/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43      1x   1x       1x     1x   1x                     1x         1x             1x       1x  
import { bindingBehavior } from 'aurelia-binding';
 
@bindingBehavior('booleanAttr')
export class BooleanBB {
 
  public bind(binding: any) {
    binding.targetObserver = new BooleanAttributeObserver(binding.target, binding.targetProperty);
  }
 
  public unbind() {
    // Empty
  }
}
 
class BooleanAttributeObserver {
 
  private useString: boolean;
 
  constructor(
    public element: HTMLElement,
    public attr: string
  ) {
    this.useString = /(?:^data-)|(?:^aria-)|\w+:/.test(attr);
  }
 
  public getValue() {
    const val = this.element.getAttribute(this.attr);
    return val || val === '' ? true : false;
  }
 
  public setValue(newValue: boolean | string) {
    if (newValue || newValue === '') {
      return this.element.setAttribute(this.attr, this.useString ? 'true' : '');
    }
    return this.useString ? this.element.setAttribute(this.attr, 'false') : this.element.removeAttribute(this.attr);
  }
 
  public subscribe() {
    const msg = `Observation of a "${this.element.nodeName}" element\'s "${this.attr}" attribute is not supported.`;
    throw new Error(msg);
  }
}