Nazar Gargol Nazar Gargol - 3 years ago 120
Javascript Question

Multiple event binding shortcut

What I am currently doing when binding same element to multiple actions in knockout is:

data-bind="event: { click: doAction,
touchend : doAction}"


My question is :
Is there some kind of shortcut notation that could be used when binding to actions?

I would expect something like :

data-bind="event: {click, touchend : doAction}"

Answer Source

There is not a built-in shortcut to do this, but it is pretty easy to use a custom binding to make your data-bind cleaner.

There are several approaches that you could take. One solution specific to click and touchend would be:

ko.bindingHandlers.clickAndTouch = {
    init: function(element, valueAccessor, allBindingsAccessor, data) {
         var action = valueAccessor(),
             newValueAccessor = function() {
                 return {
                     click: action,
                     touchend: action
                 }                     
             };

         ko.bindingHandlers.event.init.call(this, element, newValueAccessor, allBindingsAccessor, data);      
    }        
};

Then, you would bind against it like:

data-bind="clickAndTouch: doAction"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download