我需要使用Knockout格式化数据绑定格式的帮助 [英] I need help formatting a data-bind using Knockout

查看:55
本文介绍了我需要使用Knockout格式化数据绑定格式的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Knockout还是陌生的,我正在寻找格式化输出的方法.我看到了一个类似这样的例子,但是我的尝试当然没有用.

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.

这是jsfiddle的链接: http://jsfiddle.net/cezmp/

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>

这篇关于我需要使用Knockout格式化数据绑定格式的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆