在文本框中再次敲除具有相同条目的逗号分隔数字的bindingHandler [英] Knockout bindingHandler for comma separated numbers with same entry again in a textbox

查看:77
本文介绍了在文本框中再次敲除具有相同条目的逗号分隔数字的bindingHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个Knockout bindingHandler,将其格式设置为逗号分隔的数字.经过一番搜索后,我在此处找到了解决方案(感谢@nemesv解决方案),它使用 http://numeraljs.com/进行转换.

I needed to create a Knockout bindingHandler which would format the amount to comma separated numbers. After a little searching I found the solution here (Thanks to @nemesv for the solution) which uses http://numeraljs.com/ for the conversion.

活页夹如下:

ko.bindingHandlers.formatMoney = {
  init: function(element, valueAccessor) {

    var value = valueAccessor();

    var interceptor = ko.computed({
        read: function() {
            return numeral(ko.unwrap(value)).format('0,0.00');
        },
        write: function(newValue) {
            if($.trim(newValue) == '')
                value("0");
            else
                value(numeral().unformat(newValue));
        }
    }).extend({ notify: 'always' });

    if(element.tagName.toLowerCase() == 'input' )
        ko.applyBindingsToNode(element, {
            value: interceptor
        });
    else
        ko.applyBindingsToNode(element, {
            text: interceptor
        });
  }
}

我使用了它,在正常情况下它可以完美地工作.但是当与文本框一起使用时,我需要对其进行修复.

I used it and it works perfectly in normal cases. But I need to fix it when using it with textbox.

问题是正在使用可观察对象,通常仅在值实际更改时才通知它.因此,如果我每次键入一个不同的值,都会应用实际的格式化程序.例如

The issue is that an observable is being used which are normally only notified if the value actually changed. So the actual formater is applied if I type a different value every time. So for example

  • 如果我第一次输入1234,并且文本框失去焦点,它将转换为1,234.00.
  • 现在是否在文本框中再次输入1234.它不起作用,并且未调用活页夹的read方法.
  • if I type 1234 for the first time and textbox loses focus, it gets converted to 1,234.00.
  • now if you type 1234 again in the textbox. it does not work and the binder's read method is not called.

即使Observable具有相同的值,我该怎么做才能使interceptor's read方法每次触发??

What do I have to do to make the interceptor's read method fire everytime even if the observable has the same value.?

小提琴样本: http://jsfiddle.net/vEcSq/4/

谢谢.

推荐答案

您可以在可观察对象上使用valueHasMutated函数来提醒订阅者它已经更改,即使它没有更改.在interceptorwrite函数中,将以下行添加为该函数的最后一行.

You can use the valueHasMutated function on the observable to alert subscribers that it has changed, even if it hasn't. In the write function on the interceptor, add the following line as the last line of the function.

value.valueHasMutated();

我已经通过调用更新了您的jsfiddle ,并且看来工作正常.

I have updated your jsfiddle with the call and it seems to be working correctly.

这篇关于在文本框中再次敲除具有相同条目的逗号分隔数字的bindingHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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