knockoutjs - multiple bindings on click event

后端 未结 4 869
隐瞒了意图╮
隐瞒了意图╮ 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:47

    Try to use

    <span data-bind="click: function() { function1(); function2() }"></span>
    
    0 讨论(0)
  • 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:

    <div id="foo">
      <a data-bind="clickArray: [bar, baz]">Click</a>
    </div>
    

    …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/

    0 讨论(0)
  • 2020-12-16 11:02

    EDIT: I accidentally used the MooTools typeOf() without thinking. Fixed.


    Here's what I came up with. I admit it's overkill for most situations but the syntax is a bit cleaner on the template side:

    View Model:

    var ViewModel = new function() {
        this.call = function(functions,args) {
            if (!(functions instanceof Array))
                functions = [functions];
            if (!(args instanceof Array))
                args = [args];
    
            return function() {
                for (var i = 0, l = functions.length; i < l; i++) {
                    functions[i].apply(this,args);
                }
            }
        }
    
        this.testValue=ko.observable('Click me!');
        this.click1 = function(foo) {
            this.testValue('click1 ' + foo);
            alert(1);
        }
        this.click2 = function(foo) {
            this.testValue('click2 ' + foo);
            alert(2);
        }
    }
    

    and template

    <span data-bind="click:call([click1,click2],['Test value'])">Test span</span>
    
    0 讨论(0)
  • 2020-12-16 11:03

    I tried this in my code and it seems to work:

    <button data-bind="click: viewMode.bind($data, 'view'), click: itemUpdate">
    
    0 讨论(0)
提交回复
热议问题