KnockoutJS autoNumeric绑定处理程序将空值替换为0

时间:2014-12-10 17:14:35

标签: jquery knockout.js

好的,昨天一位用户帮助我获得了使用autoNumeric编写的numeric binding handler非常好的实现,但我无法弄清楚如何用0替换空字符串。在小提琴中,删除20然后选项卡,你可以看到从淘汰赛得到的整数金额是NaN。它显示0,但ko observable显然没有在幕后更新。如何将它显示0和存储0以获取空字符串?

HTML:

Integer Amount: <input type="text"  data-bind="autoNumeric:$data.Amount, settings:{mDec:0,aSep:','} " /><br />
Decimal Amount: <input type="text"  data-bind="autoNumeric:$data.OnloadAmount, settings:{mDec:3,aSep:'',vMin:0,vMax:1} " />
<p>Integer Amount:</p><p data-bind="text: Amount" />

的javascript:

ko.bindingHandlers.autoNumeric = {
    init: function (el, valueAccessor, bindingsAccessor, viewModel) {
    var $el = $(el),
        bindings = bindingsAccessor(),
        settings = bindings.settings,
        value = valueAccessor();

    $el.autoNumeric(settings);
    $el.autoNumeric('set', parseFloat(ko.utils.unwrapObservable(value()), 10));
    $el.change(function () {
        value(parseFloat($el.autoNumeric('get'), 10));
    });
    },
    update: function (el, valueAccessor, bindingsAccessor, viewModel) {
    var $el = $(el),
        newValue = ko.utils.unwrapObservable(valueAccessor()),
        elementValue = $el.autoNumeric('get'),
        valueHasChanged = (newValue != elementValue);

    if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0")) {
        valueHasChanged = true;
    }

    if (valueHasChanged) {
        if (elementValue == '')
        $el.autoNumeric('set', 0);
        else
        $el.autoNumeric('set', newValue);
    }
    }
};

var vm = function(){   
    this.Amount=ko.observable(20); 
    this.OnloadAmount=ko.observable(0.5); //onLoad Testko.bindingHandlers.autoNumeric =  {
}

ko.applyBindings(new vm());

Fiddle

1 个答案:

答案 0 :(得分:2)

嗯,你只需要写这样的东西就可以了。

更新绑定处理程序:

 if (valueHasChanged) {
      $el.autoNumeric('set', newValue);
      setTimeout(function() {
        $el.change()
      }, 0);
    }

工作小提琴 here

任何问题都告诉我们。