Friday, August 30, 2013

Knockout Custom Bindings in Durandal


Instead of using like

$("#mask").inputmask ("d/m/y" , {autoUnmask : true});


it is better to use knockout custom binding.

Define the custom binding in html or make an AMD module.

ko.bindingHandlers.inputmask = {
  init: function (element, valueAccessor, allBindingsAccessor) {
    var obj = valueAccessor(),
              allBindings = allBindingsAccessor(),
              format = allBindings.format;
    $(element).inputmask(format , obj);

    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
      $(element).inputmask('destroy');
    });
  },
  update: function (element) {
    $(element).trigger('change');
  }
};
or define this in main module.


define(['durandal/system', 'durandal/app', 'durandal/viewLocator' , 'durandal/composition'], function (system, app, viewLocator , composition) {

 composition.addBindingHandler('inputmask', {
        init: function (element, valueAccessor, allBindingsAccessor ) {
              var obj = valueAccessor(),
                  allBindings = allBindingsAccessor(),
                  format = allBindings.format;
              $(element).inputmask(format , obj);


               ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                 $(element).inputmask('destroy');
               });           

        },
        update: function (element) {
            $(element).trigger('change');
        }
    });
......
}
And you can use in view as:
< input data-bind="inputmask :  {autoUnmask: true} , format : 'd/m/y'" id="mask" type="text" / >

0 comments: