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

前端 未结 5 2004
孤独总比滥情好
孤独总比滥情好 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

    Well done, riceboyler. I took your code and extended it a little in order to use the "placeholder" property of the Masked Input Plugin:

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

    HTML with placeholder:

        
    

    HTML without placeholder:

        
    

    The KO binding works either way.

提交回复
热议问题