Eugene Mala
Eugene Mala

Reputation: 1293

Make Aurelia checkbox binding use 1\0 instead of true\false

I want to bind input type checkbox to a single variable, checkbox should be checked when variable has value 1 and unchecked if it is 0 or null. When user clicks checkbox - variable should become 1 when checked and 0 when unchecked.

Which is the proper way of doing such binding?

Upvotes: 0

Views: 745

Answers (3)

Eugene Mala
Eugene Mala

Reputation: 1293

Looks like that Aurelia way of doing this is to use value converter, especially when there are many places where you need to convert 1\0 to true\false:

export class BooleanValueConverter {
  toView(value, trueValue = 1, falseValue = 0) {
    return value === trueValue
  }

  fromView(boolean, trueValue = 1, falseValue = 0) {
    return boolean ? trueValue : falseValue;
  }
}

HTML:

<input type="checkbox" checked.bind="oneOrZeroProp | boolean"> 

This converter will work with other values for true and false as well:

<input type="checkbox" checked.bind="yesOrNoStringProp | boolean:'yes':'no'"> 

Upvotes: 1

Aurelia binding for checkboxes supports booleans or arrays of objects, numbers or strings. A standard way would be to use a boolean observable property and map its value changes to the number (0 or 1) variable:

import { observable } from "aurelia-framework";

export class App {
  @observable trueOrFalse: boolean = false;
  oneOrZero: number = 0;

  trueOrFalseChanged(newValue: boolean) {
    this.oneOrZero = this.trueOrFalse ? 1 : 0;
  }
}
<template>
  <label>
    <input type="checkbox" checked.bind="trueOrFalse" />
    Checkbox
  </label>
  Value: ${oneOrZero}
</template>

For a working example, please see: sandbox

Upvotes: 2

Abrah_dago_313
Abrah_dago_313

Reputation: 210

checked.bind="varName === 1"

and listen for click to modify varName click.delegate="setVarName()"

setVarName () { varName = varName ? 0 : 1; )

Upvotes: 1

Related Questions