I am fairly new to Knockout and I am looking for way to format the output. I saw an example that was something like this but of course my attempt is not working.
Here is the link to the jsfiddle: http://jsfiddle.net/cezmp/
<div id="VMDiv">
<table>
<thead>
<tr>
<th>Raw</th>
<th>Formatted</th>
</tr>
</thead>
<tbody>
<tr>
<td data-bind="text : SomeData "> </td>
<td data-bind="text : formatPercent(SomeData())"> </td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function formatPercent(value) {
return value.toFixed(2) + "%";
}
function vm() {
var self = this;
self.SomeData = ko.observable(62.1795972898);
}
ko.applyBindings(new vm(), document.getElementById("VMDiv"));
</script>
You could consider using a computed observable:
div id="VMDiv">
<table>
<thead>
<tr>
<th>Raw</th>
<th>Formatted</th>
</tr>
</thead>
<tbody>
<tr>
<td data-bind="text : SomeData "> </td>
<td data-bind="text : SomeDataFormatted"> </td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function vm() {
var self = this;
self.SomeData = ko.observable(62.1795972898);
self.SomeDataFormatted = ko.computed(function(){
return self.SomeData().toFixed(2) + "%";
});
}
ko.applyBindings(new vm(), document.getElementById("VMDiv"));
</script>
If you want a more generic solution you can do something like this
(function () {
ko.extenders.isCurrency = function (target, options) {
var result = ko.dependentObservable({
read: function () {
return Globalize.format(target(), "c");
},
write: target
});
result.raw = target;
return result;
};
} ());
ViewModel = function() {
this.cashIsKing = ko.observable(565345.56435535).extend({ isCurrency: true});
};
ko.applyBindings(new ViewModel());
http://jsfiddle.net/5H5AK/
edit: Instead of using true as options, you can supply a object literal with options and use that from the isCurrency extender
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With