Knockout textInput and maskedinput plugin

2020-04-19 23:28发布

Is there an easy way to use data-bind="textInput: aProperty" and add an input mask or some automatic formatting as the user types?

Using the masked input plugin kind of works, but I lose the "as-you-type" updates that Knockout's "textInput:" provides, so other parts of the script only see the change after the field loses focus (effectively behaving as a plain old "value:" binding in Knockout).

A naïve solution with a computed observable that does the formatting doesn't work because each keystroke to a field that updates itself changes the input focus to somewhere else in the page, so the user can't keep typing.

Can I make these two libraries play nice with each other or should I make my custom solution? They do a lot of things in their event handlers to be compatible with all browsers, so it's not a surprise that it's hard to make them work together, but that is also exactly why I don't want to fiddle with all those keyup, input, change, events by myself.

All previous answers on StackOverflow don't mind propagating the changes only after the field loses focus. Maybe those answers were posted before textInput was added to Knockout, so there wasn't anything better at the time. That's why I'm asking a new question.

1条回答
Explosion°爆炸
2楼-- · 2020-04-20 00:00

I've written a fiddle that uses just a computed observable, and I don't have a focus problem with it. Does this work as you expect?

var displayString = ko.observable('');
var formattedString = ko.computed({
    read: function () {
        return displayString();
    },
    write: function (newValue) {
        var f = format(newValue);
        console.debug("Format", newValue, "=", f);
        displayString(f);
    }
});

http://jsfiddle.net/csmmnq25/

查看更多
登录 后发表回答