knockout.js knockoutjs -单击事件时的多个绑定

h43kikqp  于 2022-11-10  发布在  其他
关注(0)|答案(4)|浏览(154)

我想知道是否可以在knockout.js中为一个事件创建多个绑定
例如:

<span data-bind="click: function1 function2, attr: {}"></span>
sigwle7e

sigwle7e1#

尝试使用

<span data-bind="click: function() { function1(); function2() }"></span>
wtzytmuj

wtzytmuj2#

编辑:我不小心使用了MooTools typeOf()。修正。
下面是我的想法。我承认它在大多数情况下有点过头了,但是模板方面的语法更清晰一些:
查看型号:

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);
    }
}

和模板

<span data-bind="click:call([click1,click2],['Test value'])">Test span</span>
66bbxpm5

66bbxpm53#

如何自定义简单绑定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);
        }
      }
    });
  }

};

然后 Package 一些HTML:

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

...并制作一个模型:

var viewModel = {
    bar: function () {
      alert('Bar!');
    },

    baz: function () {
      alert('Baz.');
    }
  }
}

ko.applyBindings(viewModel, document.getElementById('foo'));

工作提琴:https://jsfiddle.net/hejdav/qmfem8t3/6/

p8ekf7hl

p8ekf7hl4#

我在我的代码中尝试了这一点,它似乎工作:

<button data-bind="click: viewMode.bind($data, 'view'), click: itemUpdate">

相关问题