【问题标题】:Working with currency in knockout & javascript在淘汰赛和 javascript 中使用货币
【发布时间】:2014-05-29 10:12:52
【问题描述】:

在我的应用程序中,我有一个表格,其中包含一些钱字段。我还有一些淘汰赛的 customBinding 来处理输入并为插入的值添加正确的货币符号(例如:55 -> $55 | 55€)。

当货币符号必须在插入值之后时,问题就开始了。然后以防有人插入一些值,然后单击 Backspace 到我的 KO 绑定出现错误值。

示例

我的货币是欧元。我在输入中插入“123”,我的绑定将其更改为“123€”。然后我单击退格键,绑定中的值是“123”而不是“12€”或“12”。所以我很难了解输出值的外观。

这个问题有解决方案吗?我考虑过处理 Backspace 键或与货币符号进行一些比较,但也许有人知道更好的解决方案?

【问题讨论】:

  • 您的自定义绑定在哪里
  • 你试过 valueUpdate:afterKeyPress
  • @raheelshan 我使用了“valueUpdate”属性。我认为在这种情况下我的自定义绑定不是问题,因为这种情况很常见,是正常行为,我只为它寻找解决方案。

标签: javascript knockout.js globalization


【解决方案1】:

你可以使用extenders

ko.extenders.currency = function(target, options) {
    var result = ko.computed({
        read: target, 
        write: function(newValue) {
            var current = target();
            if((''+newValue).indexOf(options.currencySymbol) == -1){
            if (options.position == 'left') {
                target(options.currencySymbol+newValue);
            } else {
                target(newValue+options.currencySymbol);
            }}
        }
    }).extend({ notify: 'always' });

    result(target());

    return result;
};

function AppViewModel(one, two) {
    this.myNumberOne = ko.observable(one).extend({ currency: { currencySymbol : '£', position : 'left'}});
    this.myNumberTwo = ko.observable(two).extend({ currency: { currencySymbol : '£', position : 'right'}});
}

ko.applyBindings(new AppViewModel(221.2234, 123.4525));

JSFiddle

【讨论】:

  • 问题要复杂得多,我只是展示了具体问题
猜你喜欢
  • 2013-12-18
  • 2012-06-06
  • 2015-06-02
  • 2011-06-16
  • 1970-01-01
  • 2013-06-15
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多