BorisMoore / jsviews

Interactive data-driven views, MVVM and MVP, built on top of JsRender templates
http://www.jsviews.com/#jsviews
MIT License
855 stars 130 forks source link

Formatting a number in data-link ? #454

Closed carlo-fontanos closed 1 year ago

carlo-fontanos commented 2 years ago

Hi,

My code looks like this:

<input type="text" data-link="input_amount || next_bid ">
<a data-link="amount{:input_amount || next_bid}">Bid</a>

The code currently works as expected, when a user inputs a value on the input field it reflects automatically on the tag. But it no longer reflects when I format the next_bid into 2 decimal places like this:

<input type="text" data-link="input_amount || (+next_bid).toFixed(2) ">

BorisMoore commented 2 years ago

I think the best approach would be to use converters, in order, first, to convert from the number data type of your underlying data (next_bid) to the string data type displayed/returned by in an <input>, and back to number when the input is updated.

You can then choose to have the converter from number to string also format to 2 decimal places, etc etc,

$.views.converters({
  dec: function(value) {
    return value.toFixed(2); // return number as string formatted to 2 decimal places
  },
  toNum: function(val) {
    return +val; // Convert string to number
  }
});
<input data-link="{:next_bid:toNum}"/><br/><br/>
<input data-link="{dec:next_bid:toNum}"/><br/><br/>
<a data-link="next_bid">Bid</a>

<input data-link="next_bid.toFixed(2)"/> won't work because by default data-link will bind to the leaf item in the data path, in this case the 'computed' toFixed(2), (see https://www.jsviews.com/#linked-paths@deep), whereas you want to bind to next_bid.

You could specify the two-way binding to next_bid by writing <input data-link="next_bid^toFixed(2) linkTo=next_bid"/>, but even there, you still need to convert to number, and therefore to write <input data-link="{:next_bid^toFixed(2) linkTo=next_bid:toNum}"/>, so you might as well use the simpler approach above of doing everything in the dec and toNum converters...

Let me know if this works for you...

BorisMoore commented 1 year ago

Resolving as a question (not a bug)