Knockout textInput 和 maskedinput 插件 [英] Knockout textInput and maskedinput plugin
问题描述
是否有一种简单的方法可以使用 data-bind="textInput: aProperty"
并在用户键入时添加输入掩码或一些自动格式?
Is there an easy way to use data-bind="textInput: aProperty"
and add an input mask or some automatic formatting as the user types?
使用 屏蔽输入 插件类型的作品,但我失去了as-您键入的更新由 Knockout 的textInput:"提供,因此脚本的其他部分仅在字段失去焦点后才能看到更改(在 Knockout 中有效地表现为普通的旧value:"绑定).
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).
使用计算的 observable 进行格式化的幼稚解决方案不起作用,因为每次击键更新自身的字段都会将输入焦点更改为页面中的其他位置,因此用户无法继续输入.
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.
我可以让这两个库相互配合,还是应该制作我的自定义解决方案?他们在他们的事件处理程序中做了很多事情来与所有浏览器兼容,所以很难让他们一起工作并不奇怪,但这也正是我不想摆弄所有那些 keyup, input 的原因,变化,我自己的事件.
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.
StackOverflow 上的所有先前答案都不介意仅在该字段失去焦点后传播更改.也许这些答案是在 textInput 添加到 Knockout 之前发布的,所以当时没有比这更好的了.这就是为什么我要问一个新问题.
推荐答案
我写了一个 fiddle,它只使用了一个计算的 observable,我没有焦点问题.这是否如您所愿?
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);
}
});
这篇关于Knockout textInput 和 maskedinput 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!