自定义Knockout可订阅功能

时间:2017-02-13 18:01:20

标签: javascript knockout.js

我创建了一个自定义可订阅功能,将电话号码格式化为xxx-xxx-xxxx格式,效果非常好。但是,必须添加新约束,以便如果用户键入的值超过11位,则不应格式化该数字。你能告诉我为什么这段代码仍然是格式化超过11位的输入吗?

ko.subscribable.fn.formatPhoneNumber = function () {
        return ko.computed({
            read: function () {
                if (this().length > 11) {
                    return this();
                } else {
                    return this()
                        .replace(/\D+/g, "")
                        .replace(/^[01]/, "")
                        .replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
                        .substring(0, 12);
                }
            },
            write: function (value) {
                if (this(value).length > 11) {
                    this(value);
                    this.valueHasMutated();
                } else {
                    this(value.replace(/\D+/g, "")
                        .replace(/^[01]/, "")
                        .replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
                        .substring(0, 12));
                    this.valueHasMutated();
                }
            },
            owner: this
        }).extend({ notify: 'always' });
    };

1 个答案:

答案 0 :(得分:0)

这似乎是一个逻辑错误:

if (this(value).length > 11) { ...

IMO应该是:

if (value.length > 11) { ...