2012-08-01 36 views
5

我對Knockout相當陌生,並且正在尋找格式化輸出的方式。我看到一個這樣的例子,但我的嘗試當然不起作用。我需要幫助使用Knockout格式化數據綁定

這裏是鏈接到的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> 

回答

7

你可以考慮使用一個計算觀察到:

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> 
+0

這將工作但不是我的使用案例的理想選擇。我確實在Knkockout網站上找到了這個。 http://knockoutjs.com/examples/cartEditor.html它有一個像我想要的例子,但我仍然有問題讓我的代碼正常工作。我會繼續堵塞。 – Jim 2012-08-01 02:53:21

+0

就像這是一個片狀的簡單例子。我做了另一個簡單的jsfiddle http://jsfiddle.net/cezmp/1/它是上面cartEditor演示的一個剝離版本。它在jsfiddle中不起作用,但它「適用於」我的網站上的測試html頁面。 – Jim 2012-08-01 03:08:14

+0

仔細看一下我上面的示例,計算出的observable會執行格式化,然後直接將數據綁定到元素的文本。這裏是你的小提琴的更新:http://jsfiddle.net/cezmp/3/ – KodeKreachor 2012-08-01 04:12:26

5

如果你想要一個更通用的解決方案,你可以做這樣的事情

(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/

編輯:您可以提供一個帶有選項的對象文本,並使用isCurrency擴展器中的對象文本