Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need help formatting a data-bind using Knockout

Tags:

knockout.js

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>
like image 584
Jim Avatar asked Aug 01 '12 00:08

Jim


2 Answers

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>
like image 122
KodeKreachor Avatar answered Sep 23 '22 04:09

KodeKreachor


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

like image 43
Anders Avatar answered Sep 24 '22 04:09

Anders