knockoutjs - multiple bindings on click event

后端 未结 4 894
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 10:27

I would like to know if it is possible to create multiple bindings on an event in knockout.js

example:



        
4条回答
  •  孤街浪徒
    2020-12-16 10:55

    How 'bout custom simple binding clickArray:

    ko.bindingHandlers.clickArray = {
    
      init: function (element, valueAccessor) {
        var handlers = valueAccessor();
    
        ko.applyBindingsToNode(element, {
          click: function () {
            for (var i = 0; i < handlers.length; i++) {
              handlers[i].apply(this, arguments);
            }
          }
        });
      }
    
    };
    

    Then you wrap some HTML:

    
    

    …and make a model:

    var viewModel = {
        bar: function () {
          alert('Bar!');
        },
    
        baz: function () {
          alert('Baz.');
        }
      }
    }
    
    ko.applyBindings(viewModel, document.getElementById('foo'));
    

    Working fiddle: https://jsfiddle.net/hejdav/qmfem8t3/6/

提交回复
热议问题