A bi-directional value converter utilizes two methods in your Value Converter class: toView
and fromView
these methods are aptly named to signify which direction the data is flowing.
In our example we will be creating a prepend Value Converter which will make sure that an amount entered in our app has a dollar sign infront of it.
prepend.js
export class PrependValueConverter {
/**
* This is the value being sent back to the view
*
*/
toView(value) {
return `$${value}`;
}
/**
* Validate the user entered value
* and round it to two decimal places
*
*/
fromView(value) {
return parseFloat(value.toString().replace('$', '')).toFixed(2);
}
}
Using it:
export class MyViewModel {
amount = '';
}
<template>
<require from="./prepend"></require>
<h1>Current amount: ${amount}</h1>
<label>Enter amount:</label>
<input type="text" id="amount" value.bind="amount | prepend & debounce:500">
</template>
Worth noting is that we are using a binding behaviour to limit the rate of which our value is updated or it will be updated every time you type and not be the intended behaviour.