Can calculation be used in the calculation?

I have a custom binding that I use to format percentages.

ko.bindingHandlers.textPercent = { //init: function (element, valueAccessor, allBindingsAccessor, viewModel) { // //init logic //}, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var val = parseFloat(ko.utils.unwrapObservable(valueAccessor())); if ($.isNumeric(val)) { $(element).text((val * 100).toFixed(2))+"%"; } else { $(element).text("#Error"); } } } 

using:

 <span data-bind="textPercent: amount" ></span> <span data-bind="textPercent: amount()/2" ></span> 

It works fine, but I would like to use a different number of fixed digits, so I made an expander:

 ko.extenders.percent = function (target, precision) { var result = ko.computed({ read: function () { return (target()*100).toFixed(precision)+"%"; }, write: function (newValue) { target(parseFloat(newValue) / 100); } }); return result; }; 

using:

 <span data-bind="text: amount.extend({ percent: 2 })" ></span> <span data-bind="text: (amount()/2).extend({ percent: 2 })" ></span> 

The problem is that it does not work with inline computing.

Suggestions?

http://jsfiddle.net/eRapL/4/

+4
source share
1 answer

You should wrap your expression with ko.observable()

Example:

 text extend percent: <span data-bind="text: ko.observable(amount() / 2).extend({ percent: 2 })" ></span><br/> 

Take a look: http://jsfiddle.net/c7Qx7/1/

+4
source

Source: https://habr.com/ru/post/1412841/


All Articles