我想知道是否可以在knockout.js中为一个事件创建多个绑定例如:
<span data-bind="click: function1 function2, attr: {}"></span>
sigwle7e1#
尝试使用
<span data-bind="click: function() { function1(); function2() }"></span>
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>
66bbxpm53#
如何自定义简单绑定clickArray:
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/
p8ekf7hl4#
我在我的代码中尝试了这一点,它似乎工作:
<button data-bind="click: viewMode.bind($data, 'view'), click: itemUpdate">
4条答案
按热度按时间sigwle7e1#
尝试使用
wtzytmuj2#
编辑:我不小心使用了MooTools typeOf()。修正。
下面是我的想法。我承认它在大多数情况下有点过头了,但是模板方面的语法更清晰一些:
查看型号:
和模板
66bbxpm53#
如何自定义简单绑定
clickArray
:然后 Package 一些HTML:
...并制作一个模型:
工作提琴:https://jsfiddle.net/hejdav/qmfem8t3/6/
p8ekf7hl4#
我在我的代码中尝试了这一点,它似乎工作: