Skip to content

HOWTO: Integration with Knockoutjs

penihel edited this page Aug 28, 2014 · 1 revision

To use the "inputmask" integrated with "knockoutjs", we suggest using the following Custom binding:

The Custom Binding

ko.bindingHandlers.inputmask =
{
    init: function (element, valueAccessor, allBindingsAccessor) {

        var mask = valueAccessor();

        var observable = mask.value;

        if (ko.isObservable(observable)) {

            $(element).on('focusout change', function () {

                if ($(element).inputmask('isComplete')) {
                    observable($(element).val());
                } else {
                    observable(null);
                }

            });
        }

        $(element).inputmask(mask);


    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var mask = valueAccessor();

        var observable = mask.value;

        if (ko.isObservable(observable)) {

            var valuetoWrite = observable();

            $(element).val(valuetoWrite);
        }
    }

};

How use

<input type="text" data-bind="inputmask: { value:NameOfObservable , mask:'99.999-99'}" />