[英]KnockoutJS: Handle event capture phase
Let's consider the standard way to bind a generic event to a ViewModel method using KnockoutJS:让我们考虑使用 KnockoutJS 将通用事件绑定到 ViewModel 方法的标准方法:
<div data-bind="event: { mousedown: handler }"></div>
This code will add handler
as a listener on the mousedown
event to the <div>
.此代码会将handler
作为mousedown
事件的侦听器添加到<div>
。 As any other handler, it is attached to the target and bubble phase of the event.与任何其他处理程序一样,它附加到事件的目标和冒泡阶段。
However, I don't see a way of attaching a handler to the capture phase of an event without resorting to a manual call to addEventListener
outside of the MVVM pattern provided by Knockout JS.但是,我没有看到一种将处理程序附加到事件捕获阶段的方法,而无需在 Knockout JS 提供的 MVVM 模式之外手动调用addEventListener
。
Is it possible to bind an handler to the event capture phase using data-bind
in Knockout JS?是否可以使用 Knockout JS 中的data-bind
绑定将处理程序绑定到事件捕获阶段?
When you need to do DOM manipulation that an existing binding handler doesn't do, you write a custom binding handler.当您需要执行现有绑定处理程序无法执行的 DOM 操作时,您可以编写自定义绑定处理程序。 Here's a simple demonstration of a capture-phase event handler.这是捕获阶段事件处理程序的简单演示。 You'll have to look at the debugging console to see the output.您必须查看调试控制台才能看到输出。
ko.bindingHandlers.captureEvent = { init: function (element, valueAccessor) { var arg = valueAccessor(); for (var eventName in arg) { element.addEventListener(eventName, arg[eventName], true); } } }; vm = { handler: function (event) { console.debug(event.currentTarget.id); } }; ko.applyBindings(vm);
#d1 { background-color: red; height: 35em; width: 35em; } #d2 { background-color: green; height: 25em; width: 25em; } #d3 { background-color: blue; height: 15em; width: 15em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div id="d1" data-bind="captureEvent: {mousedown: handler}"> <div id="d2" data-bind="captureEvent: {mousedown: handler}"> <div id="d3" data-bind="captureEvent: {mousedown: handler}"></div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.