Knockout textInput and maskedinput plugin

泄露秘密 提交于 2019-12-02 14:27:46

问题


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:


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/



来源:https://stackoverflow.com/questions/30406535/knockout-textinput-and-maskedinput-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!