Format knockout observable with commas and/or decimal places within html data binding, NOT in viewmodel

余生长醉 提交于 2020-01-05 04:02:18

问题


I've seen RP Niemeyer's answer here: Formatting rules for numbers in KnockoutJS but it doesn't seem to fit my situation.

My viewmodel is tightly bound with breeze entities for a start, so I cannot easily mess with the individual table fields. There are c. 40 fields that contain numerical impact calculation results, often to 9 or 10 decimal places. It is essential that the raw result is left untouched in the viewmodel.

RP Niemeyer's "extend" based solution seems to suit more a situation where the observable is manually created. I'd like to be able to do the formatting within the html data-bind itself as this allows me to leave things untouched in the database and just limit the display of the calculation to 3 or 4 decimal places.

I'd like to be able to do:

<div data-bind="text: myValue, precision: 1"></div>

using the extend model such as this if possible?

ko.extenders.numeric = function(target, precision) {
    var result = target;

    result.formatted = ko.dependentObservable({
        read: function() {
           return target().toFixed(precision); 
        },
        write: target 
    });

    return result.formatted;
};

but as it is, this currently doesn't work so I'm probably missing something really obvious.


回答1:


This answer: Formatting rules for numbers in KnockoutJS contains a numericText binding that might work in your scenario.

Using a binding is definitely helpful in scenarios where it is not easy or convenient to hook into the creation of the observables/properties of your view model.



来源:https://stackoverflow.com/questions/19914330/format-knockout-observable-with-commas-and-or-decimal-places-within-html-data-bi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!