Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout custom binding handlers - multiple arguments and function callbacks best practice?

I recently created a binding handler to incorporate the JQuery Validation plugin into a form using the data-bind syntax. I found myself needing to supply more than one piece of info to the handler. I needed to supply a flag to enforce validation and a callback to fire once validation passed.

Questions:

  1. What is the best practice for supplying multiple args? I just relied on the object notation syntax, but could also supply another binding and check that binding via the "allBindings" param passed to the handler...

  2. What is the best practice for supplying a callback function to a handler?

Below is the js code defining the handler and the html code to apply the handler:

     <form id="step1" 
        data-bind="jqValidation:{enforce: true, 
                                 submitHandler: doSomethingInVM}">
           <fieldset data-bind="with:searchRequest">
            //fields
           </fieldset>
           <button type="submit">submit</button>
     </form>

     ko.bindingHandlers.jqValidation = {

        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var accessor = valueAccessor();
            //need unwrapobservable??
            if (accessor.enforce) {
                $(element).find(':submit').removeClass('cancel');
                $(element).validate({
                    submitHandler: function () {
                        if ($.isFunction(accessor.submitHandler))
                            accessor.submitHandler();
                    }
                });
            } else
                $(element).find(':submit').addClass('cancel');
        }
    };
like image 664
drogon Avatar asked Mar 07 '12 16:03

drogon


1 Answers

Your approach here follows the pattern used by KO itself so I think it is perfectly valid. Granted you could also use the allBindingsAccessor. The way I have interpreted the usage of this method is to

  1. Share properties between multiple bindings, for example a bubbleEvent binding could be used to indicate to any other binding that deals with events not to bubble them.
  2. To allow complex binding handlers to be aware of other bindings and adjust their behavior.

The best practice for passing handlers is to have them as named members on your view model rather than inline on the binding.

like image 149
madcapnmckay Avatar answered Dec 22 '22 21:12

madcapnmckay