Aurelia 委托 vs 触发器:你怎么知道什么时候使用委托或触发器?

Aurelia delegate vs trigger: how do you know when to use delegate or trigger?

我正在尝试学习如何使用 Aurelia 框架。在这样做的过程中,我正在阅读文档 here regarding their method of binding events. The documentation suggests using delegate by default. I have forked the plunkr that they provided in one of their blog posts and added a little bit to it. The full plunk is here.


app.html

<template>
    <input value.bind="pageInput" blur.delegate="showAlert()" placeholder="delegate()" />
    <input value.bind="pageInput" blur.trigger="showAlert()" placeholder="trigger()" />

    <button type="button" click.delegate="showAlert()">delegate()</button>
    <button type="button" click.trigger="showAlert()">trigger()</button>
</template>

app.js

export class App {
  showAlert() {
    alert('showAlert()');
  }
}

正如您在 plunkr 中看到的那样,blur.trigger/click.delegate/click.trigger 都会触发事件,但是 blur.delegate 没有。

为什么会这样?

如何确定 .delegate 何时无法正常工作(当然无需手动测试)?

使用 delegate 除非您不能使用 delegate

事件委托是一种用于提高应用程序性能的技术。它利用大多数 DOM 事件的“冒泡”特性,大大减少了事件订阅的数量。使用事件委托,处理程序不会附加到单个元素。相反,单个事件处理程序附加到顶级节点,例如 body 元素。当事件冒泡到这个共享的顶级处理程序时,事件委托逻辑会根据事件的 target.

调用适当的处理程序

要了解 event delegation 是否可以用于特定事件,google mdn [event name] event。事实上,在任何与 google 相关的网络平台搜索之前使用 mdn 通常 returns 来自 Mozilla 开发者网络的高质量结果。进入活动的 MDN 页面后,检查活动是否 bubbles。只有冒泡的事件才能与 Aurelia 的 delegate 绑定命令一起使用。 blurfocusloadunload 事件不会冒泡,因此您需要使用 trigger 绑定命令来订阅这些事件。

这是 MDN page for blur。它有关于模糊和焦点事件的事件委托技术的更多信息。

上述一般指导的例外情况:

满足以下条件时,在按钮上使用 trigger

  1. 您需要禁用该按钮。
  2. 按钮的内容由其他元素组成(而不只是文本)。

这将确保对禁用按钮的子项的点击不会冒泡到委托事件处理程序。更多信息 here.

在某些 iOS 用例中将 trigger 用于 click

iOS 不会对 abuttoninputselect 以外的元素冒泡单击事件。如果您在 div 等非输入元素上订阅 click 并以 iOS 为目标,请使用 trigger 绑定命令。 更多信息 here and here.

关于这一点,如果 Aurelia 在捕获阶段监听事件,模糊委托将起作用,但这在 Aurelia 中是不可行的。如果有人可以提供一些提示如何在 Aurelia

中捕获事件,将会很有趣

在这种情况下,以下将起作用:

<template>
    <input blur.delegate-capture='showAlert()' />
</template>