KnockoutJS binding messes with input mask

守給你的承諾、 提交于 2019-12-04 18:24:18

I don't think this is a knockout issue, but an issue with the way the masked input plugin is designed: Your initial value must match the mask criteria. Even if you get rid of knockout and just use jQuery's val() function to set the value to "1231231234", you'll see the same behavior.

UPDATE

Sorry, missed your "works" link. I was going to suggest a custom binding handler in the first place. Looks like this is the way to go. It applies the masking after the text has been updated by knockout, and then updates the view model with the new, masked value (if that's what you want):

ko.bindingHandlers.maskedInput = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        ko.bindingHandlers.value.init(element, valueAccessor, allBindings, viewModel, bindingContext);
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        ko.bindingHandlers.value.update(element, valueAccessor, allBindings, viewModel, bindingContext);
        $(element).mask(allBindings.get('mask'));
        valueAccessor()($(element).val());
    }
};

Here's your updated fiddle: http://jsfiddle.net/8r6fe/3/

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