Is there masked input plugin for knockout.js using extenders?

前端 未结 5 2062
孤独总比滥情好
孤独总比滥情好 2021-02-02 14:21

I\'ve seen this post - it shows one possible solution. But I would like to have a more elegant way of doing masked input.

It should also play nicely with knockout valida

5条回答
  •  耶瑟儿~
    2021-02-02 15:10

    If you wanted to use the excellent Masked Input Plugin in Knockout, it's pretty easy to write a basic custom binding rather than an extender.

    ko.bindingHandlers.masked = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            var mask = allBindingsAccessor().mask || {};
            $(element).mask(mask);
            ko.utils.registerEventHandler(element, 'focusout', function() {
                var observable = valueAccessor();
                observable($(element).val());
            });
        }, 
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            $(element).val(value);
        }
    };
    

    And then in your HTML:

    
    
    

    And so on with various masks. This way, you can just put the mask right in your databinding, and it allows a ton of flexibility.

提交回复
热议问题