> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/interaction/event-handling/event-propagation.md.

# 事件传播

当一个事件被触发后，它会沿着事件响应链进行传播。如果节点上设置了相应类型的事件处理器属性，则节点可以在事件传播过程中监听到对应事件甚至进行拦截。

除此之外，Lynx 还提供了跨元件事件监听、事件切面接口、`GlobalEventEmitter` 来实现特殊的事件传播。

## 事件处理器属性

通过设置事件处理器属性，开发者可以决定在事件传播的哪个阶段（或跨元件）监听或拦截该事件，并指定事件触发时调用的处理函数。这些事件处理器属性的命名通常由绑定的事件类型和事件名称组成。

| 事件类型            | 说明                   |
| --------------- | -------------------- |
| `bind`          | 冒泡阶段监听事件，不拦截事件冒泡。    |
| `catch`         | 冒泡阶段监听事件，拦截事件冒泡。     |
| `capture-bind`  | 捕获阶段监听事件，不拦截事件捕获和冒泡。 |
| `capture-catch` | 捕获阶段监听事件，拦截事件捕获和冒泡。  |
| `global-bind`   | 跨元件监听事件。             |

特别地，当事件处理函数是[主线程脚本](/zh/react/main-thread-script.md)时，需要在事件处理器属性名称前添加 `main-thread:` 前缀，以确保该处理函数在主线程中执行。

## 事件响应链

事件响应链是指由可以响应事件的节点组成的一个链表。一般来说，事件响应链由页面根节点到动作实际触发的节点的路径组成。然而，对于非[触摸事件](/zh/api/lynx-api/event/touch-event.md)，事件响应链只包含动作实际触发的节点。

**示例 1:**

**下面是一个示例: event**

**Entry:** `src/event_chain`
**Bundle:** `dist/event_chain.lynx.bundle` | Web: `dist/event_chain.web.bundle`

```tsx {50,65,78,95,108}
import { root, useState } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export default function App() {
  const [tap, setTap] = useState<boolean>(false);
  const [tap1, setTap1] = useState<boolean>(false);
  const [tap11, setTap11] = useState<boolean>(false);
  const [tap2, setTap2] = useState<boolean>(false);
  const [tap22, setTap22] = useState<boolean>(false);

  function handleTap(e: TouchEvent) {
    if (e.currentTarget.id === "tap") {
      setTap(!tap);
    }
    if (e.currentTarget.id === "tap1") {
      setTap1(!tap1);
    }
    if (e.currentTarget.id === "tap11") {
      setTap11(!tap11);
    }
    if (e.currentTarget.id === "tap2") {
      setTap2(!tap2);
    }
    if (e.currentTarget.id === "tap22") {
      setTap22(!tap22);
    }
  }

  function handletouchstart(e: TouchEvent) {
    setTap(false);
    setTap1(false);
    setTap11(false);
    setTap2(false);
    setTap22(false);
  }

  return (
    <view
      id="tap"
      style={{
        width: "calc(100% - 40px)",
        height: "90%",
        margin: "20px",
        borderRadius: "10px",
        boxShadow: "0 0 5px 5px #ccc",
        backgroundColor: tap ? "rgb(255, 179, 0)" : "white",
        justifyContent: "center",
        alignItems: "center",
      }}
      bindtap={handleTap}
      capture-bindtouchstart={handletouchstart}
    >
      <view
        id="tap1"
        style={{
          width: "70%",
          height: "40%",
          marginBottom: "25px",
          borderRadius: "10px",
          boxShadow: "0 0 5px 5px #ccc",
          backgroundColor: tap1 ? "rgb(255, 179, 0)" : "white",
          justifyContent: "center",
          alignItems: "center",
        }}
        bindtap={handleTap}
      >
        <view
          id="tap11"
          style={{
            width: "60%",
            height: "45%",
            borderRadius: "10px",
            boxShadow: "0 0 5px 5px #ccc",
            backgroundColor: tap11 ? "rgb(255, 179, 0)" : "white",
            justifyContent: "center",
            alignItems: "center",
          }}
          bindtap={handleTap}
        >
          <text user-interaction-enabled={false} style={{ color: "green" }}>click me 1</text>
        </view>
      </view>
      <view
        id="tap2"
        style={{
          width: "70%",
          height: "40%",
          marginTop: "25px",
          borderRadius: "10px",
          boxShadow: "0 0 5px 5px #ccc",
          backgroundColor: tap2 ? "rgb(255, 179, 0)" : "white",
          justifyContent: "center",
          alignItems: "center",
        }}
        bindtap={handleTap}
      >
        <view
          id="tap22"
          style={{
            width: "60%",
            height: "45%",
            borderRadius: "10px",
            boxShadow: "0 0 5px 5px #ccc",
            backgroundColor: tap22 ? "rgb(255, 179, 0)" : "white",
            justifyContent: "center",
            alignItems: "center",
          }}
          bindtap={handleTap}
        >
          <text user-interaction-enabled={false} style={{ color: "red" }}>click me 2</text>
        </view>
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



在上面这个例子中，当用户点击页面，事件响应链上的节点背景色会被置为橙色。

## 事件捕获

事件在事件响应链上会依次经过事件捕获和事件冒泡两个阶段。事件在事件捕获阶段会从页面根节点开始，沿着事件响应链向下传播，直到动作实际触发的节点。在事件捕获阶段，设置了 `capture-bind` 类型的事件处理器属性的节点能够监听到相应事件。

**示例 2:**

**下面是一个示例: event**

**Entry:** `src/event_capture`
**Bundle:** `dist/event_capture.lynx.bundle` | Web: `dist/event_capture.web.bundle`

```tsx {7-9,14}
import { root, useState } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export default function App() {
  const [cnt, setCnt] = useState<number>(0);

  function handleTap(e: TouchEvent) {
    setCnt(cnt + 1);
  }

  return (
    <view
      style={{ width: "100%", height: "90%" }}
      capture-bindtap={handleTap}
    >
      <view
        style={{
          width: "calc(100% - 10px)",
          height: "150px",
          margin: "5px",
          borderWidth: "2px",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <text>
          Counts the number of clicks on a page: <text style={{ color: "red" }}>{cnt}</text>
        </text>
      </view>
      <scroll-view
        scroll-orientation="vertical"
        style={{ width: "100%", height: "calc(100% - 150px)" }}
      >
        {[0, 1, 2, 3, 4, 5, 6].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "150px",
                margin: "5px",
                backgroundColor: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${
                  Math.floor(Math.random() * 256)
                })`,
                borderRadius: "5px",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <text>item-{item + 1}</text>
            </view>
          );
        })}
      </scroll-view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



在上面这个例子中，由于事件传播是从捕获阶段开始的，并且捕获阶段从根节点开始，因此，当用户点击页面时，根节点始终能够监听到 `tap` 事件，进而实现统计页面点击次数的功能。

## 事件冒泡

在事件冒泡阶段，事件会从动作实际触发的节点，沿着事件响应链向上传播，直到页面根节点。在事件冒泡阶段，设置了 `bind` 类型的事件处理器属性的节点能够监听到相应事件。

**示例 3**

**下面是一个示例: event**

**Entry:** `src/event_bubble`
**Bundle:** `dist/event_bubble.lynx.bundle` | Web: `dist/event_bubble.web.bundle`

```tsx {7-12,23}
import { root, useState } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export default function App() {
  const [bgColor, setBgColor] = useState<string>("white");

  function handleTap(e: TouchEvent) {
    const rndCol = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${
      Math.floor(Math.random() * 256)
    })`;
    setBgColor(rndCol);
  }

  return (
    <view
      style={{
        width: "100%",
        height: "100%",
        backgroundColor: bgColor,
        justifyContent: "center",
        alignItems: "center",
      }}
      bindtap={handleTap}
    >
      <view
        style={{
          width: "100px",
          height: "50px",
          borderRadius: "5px",
          backgroundColor: "gray",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <text style={{ color: "red" }}>click me</text>
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



在上面这个例子中，当用户点击页面任意节点时，事件会默认从子节点冒泡到父节点，因此，父节点始终能够监听到 `tap` 事件进而改变节点的背景颜色。

## 事件拦截

在事件传播的过程中，事件可以被中途拦截，从而阻止事件继续传播。当节点上设置了 `catch` 类型的事件处理器属性时，事件在传播到该节点时会被拦截，不再继续传播。

**示例 4**

**下面是一个示例: event**

**Entry:** `src/event_static_catch`
**Bundle:** `dist/event_static_catch.lynx.bundle` | Web: `dist/event_static_catch.web.bundle`

```tsx {7-12,23,34}
import { root, useState } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export default function App() {
  const [bgColor, setBgColor] = useState<string>("white");

  function handleTap(e: TouchEvent) {
    const rndCol = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${
      Math.floor(Math.random() * 256)
    })`;
    setBgColor(rndCol);
  }

  return (
    <view
      style={{
        width: "100%",
        height: "100%",
        backgroundColor: bgColor,
        justifyContent: "center",
        alignItems: "center",
      }}
      bindtap={handleTap}
    >
      <view
        style={{
          width: "100px",
          height: "50px",
          borderRadius: "5px",
          backgroundColor: "gray",
          justifyContent: "center",
          alignItems: "center",
        }}
        catchtap={(e: TouchEvent) => {}}
      >
        <text style={{ color: "red" }}>click me</text>
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



在上面这个例子中，由于 `click me` 区域设置了静态拦截 `tap` 事件，所以仅当点击非 `click me` 区域，事件才会冒泡到父节点，节点的背景颜色才会改变。

## 在主线程脚本中阻止事件冒泡

当与[主线程脚本](/zh/react/main-thread-script.md)一起使用时，可以通过调用事件对象的 [`stopPropagation`](/zh/api/lynx-api/event/event.md#stoppropagation) 方法来阻止事件冒泡。

**示例 5:**

**下面是一个示例: event**

**Entry:** `src/event_stop_propagation`
**Bundle:** `dist/event_stop_propagation.lynx.bundle` | Web: `dist/event_stop_propagation.web.bundle`

```tsx {34}
import { root, runOnBackground, useState } from "@lynx-js/react";
import "./index.css";
import type { MainThread } from "@lynx-js/types";

export default function App() {
  const [active, setActive] = useState({ outer: false, middle: false, inner: false });

  // Utility to flash a box when it's clicked
  const flashBT = (key: "outer" | "middle" | "inner") => {
    setActive((prev) => ({ ...prev, [key]: true }));
    setTimeout(() => setActive((prev) => ({ ...prev, [key]: false })), 200);
  };

  // Utility to flash a box when it's clicked
  const flash = (
    key: "outer" | "middle" | "inner",
  ) => {
    "main thread";
    runOnBackground(flashBT)(key);
  };

  function handleOuterTap(e: MainThread.TouchEvent) {
    "main thread";
    flash("outer");
  }

  function handleMiddleTap(e: MainThread.TouchEvent) {
    "main thread";
    flash("middle");
  }

  function handleInnerTap(e: MainThread.TouchEvent) {
    "main thread";
    e.stopPropagation(); // ✋ stop event bubbling
    flash("inner");
  }

  return (
    <view
      main-thread:bindtap={handleOuterTap}
      className={`box outer ${active.outer ? "active" : ""}`}
    >
      <text>Outer {active.outer ? "(active)" : "(inactive)"}</text>
      <view
        main-thread:bindtap={handleMiddleTap}
        className={`box middle ${active.middle ? "active" : ""}`}
      >
        <text>Middle {active.middle ? "(active)" : "(inactive)"}</text>
        <view
          main-thread:bindtap={handleInnerTap}
          className={`box inner ${active.inner ? "active" : ""}`}
        >
          <text>Inner (click me, stops propagation) {active.inner ? "(active)" : "(inactive)"}</text>
        </view>
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



在上面的示例中，点击内部元素不会触发外部元素的 `tap` 事件。

## 跨元件事件监听 No Web
一般来说，当节点不在事件响应链上时，事件无法被监听到。Lynx 提供了一种跨元件事件监听的方式，使得开发者能够在任意节点上注册事件监听并接收到相应事件。

例如，开发者可以在某个节点上设置 `global-bind` 类型的事件处理器属性来监听 `tap` 事件，当任意节点被点击时，该节点能够监听到 `tap` 事件，进而实现统计页面点击次数的功能。

**示例 5:**

**下面是一个示例: event**

**Entry:** `src/event_global_bind`
**Bundle:** `dist/event_global_bind.lynx.bundle` | Web: `dist/event_global_bind.web.bundle`

```tsx {8-10,12-14,19-20,47-48}
import { root, useState } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export function ComponentA() {
  const [scrollContainer, setScrollContainer] = useState<string>("");
  const [cnt, setCnt] = useState<number>(0);

  function handleScroll(e: TouchEvent) {
    setScrollContainer(e.target.id);
  }

  function handleTap(e: TouchEvent) {
    setCnt(cnt + 1);
  }

  return (
    <view
      style={{ width: "100%", height: "100%", justifyContent: "center", alignItems: "center" }}
      global-bindscroll={handleScroll}
      global-bindtap={handleTap}
    >
      <text>
        Counts the number of clicks on a page: <text style={{ color: "red" }}>{cnt}</text>
      </text>
      <text>
        Current scroll container: <text style={{ color: "green" }}>{scrollContainer}</text>
      </text>
    </view>
  );
}

export function ComponentB() {
  return (
    <view
      style={{
        width: "calc(100% - 10px)",
        height: "calc(100% - 45px)",
        marginTop: "40px",
        marginLeft: "5px",
        marginRight: "5px",
        marginBottom: "5px",
      }}
    >
      <scroll-view
        scroll-orientation="vertical"
        style={{ width: "100%", height: "50%", borderWidth: "2px" }}
        id="scroll-1"
        bindscroll={(e) => {}}
      >
        {[0, 1, 2, 3, 4, 5, 6].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "200px",
                margin: "5px",
                backgroundColor: "orange",
                borderRadius: "5px",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <text>scroll-1-item-{item + 1}</text>
            </view>
          );
        })}
      </scroll-view>
      <scroll-view
        scroll-orientation="vertical"
        style={{ width: "100%", height: "calc(50% - 10px)", marginTop: "10px", borderWidth: "2px" }}
        id="scroll-2"
        bindscroll={(e) => {}}
      >
        {[0, 1, 2, 3, 4, 5, 6].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "200px",
                margin: "5px",
                backgroundColor: "purple",
                borderRadius: "5px",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <text>scroll-2-item-{item + 1}</text>
            </view>
          );
        })}
      </scroll-view>
    </view>
  );
}

export default function App() {
  return (
    <view style={{ width: "100%", height: "90%" }}>
      <view style={{ width: "100%", height: "150px", backgroundColor: "yellow" }}>
        <view style={{ position: "absolute" }}>
          <text style={{ color: "blue" }}>ComponentA</text>
        </view>
        <ComponentA />
      </view>
      <view style={{ width: "100%", height: "calc(100% - 165px)", marginTop: "15px", backgroundColor: "#ccc" }}>
        <view style={{ position: "absolute" }}>
          <text style={{ color: "blue" }}>ComponentB</text>
        </view>
        <ComponentB />
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



需要注意的是，对于非[触摸事件](/zh/api/lynx-api/event/touch-event.md)，需要被监听节点设置了非跨元件事件监听类型的事件处理器属性。另外，开发者还可以在节点上设置 `global-target` 来指定仅监听节点 [`id`](/zh/api/elements/built-in/view.md#id) 为特定值的事件（类型为 `string`，可以指定多个 [`id`](/zh/api/elements/built-in/view.md#id)，用逗号分隔）。

## 事件切面接口

有时候，开发者可能需要在某处统一监听并处理特定类型的事件，并且不依赖元件注册事件监听。例如，统计页面上所有触发的 `tap` 事件。这时，开发者可以通过 Lynx 提供的事件切面接口（[`beforePublishEvent`](/zh/api/lynx-api/lynx/lynx-before-publish-event.md)）来实现相应功能。

**示例 6:**

**下面是一个示例: event**

**Entry:** `src/event_aop`
**Bundle:** `dist/event_aop.lynx.bundle` | Web: `dist/event_aop.web.bundle`

```tsx {7-12,65}
import { root, useMemo, useState } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export default function App() {
  const [cnt, setCnt] = useState<number>(0);

  useMemo(() => {
    "background-only";
    lynx.beforePublishEvent.add("tap", () => {
      setCnt((cnt) => cnt + 1);
    });
  }, []);

  return (
    <view
      style={{ width: "100%", height: "90%" }}
    >
      <view
        style={{
          width: "calc(100% - 10px)",
          height: "150px",
          margin: "5px",
          borderWidth: "2px",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <text>
          Counts the number of clicks on a page: <text style={{ color: "red" }}>{cnt}</text>
        </text>
      </view>
      <scroll-view
        scroll-orientation="vertical"
        style={{ width: "100%", height: "calc(100% - 150px)" }}
      >
        {[0, 1].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "150px",
                margin: "5px",
                backgroundColor: "yellow",
                borderRadius: "5px",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <text>{"Don't listen tap event-" + (item + 1)}</text>
            </view>
          );
        })}
        {[0, 1, 2, 3].map((item) => {
          return (
            <view
              style={{
                width: "calc(100% - 10px)",
                height: "150px",
                margin: "5px",
                backgroundColor: "orange",
                borderRadius: "5px",
                justifyContent: "center",
                alignItems: "center",
              }}
              bindtap={(e: TouchEvent) => {}}
            >
              <text>{"Listen tap event-" + (item + 1)}</text>
            </view>
          );
        })}
      </scroll-view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



事件切面接口是一种切面编程，通过在事件触发处注入相应接口，实现触发特定事件时将事件同时转发到某处。该接口仅在 BTS 上下文中实现的，因此，只有在后台线程中才能使用，并且只有事件处理函数触发时才能监听到对应事件。

## `GlobalEventEmitter`

有时候，开发者可能需要在不同的元件、组件之间传递事件，或者需要在客户端和前端之间传递事件，并且不依赖元件注册事件监听。这时，开发者可以通过 `GlobalEventEmitter` 来实现一个页面中事件的全局范围传递。

开发者可以通过 [`lynx.getJSModule`](/zh/api/lynx-api/lynx/lynx-get-js-module.md) 获取 `GlobalEventEmitter` 对象，其提供如下接口：

| 函数名称                 | 函数说明                  | 函数传参                              |
| -------------------- | --------------------- | --------------------------------- |
| `addListener`        | 订阅事件，注册事件监听器。         | `(eventName, listener, context?)` |
| `removeListener`     | 移除特定事件的指定监听器。         | `(eventName, listener)`           |
| `removeAllListeners` | 移除特定事件的所有监听器。         | `(eventName)`                     |
| `toggle`             | 广播指定事件名称的事件，支持多个透传参数。 | `(eventName, ...data)`            |
| `trigger`            | 广播指定事件名称的事件，支持一个透传参数。 | `(eventName, params)`             |

需要注意的是，`GlobalEventEmitter` 只在 BTS 上下文中支持，因此，只有在后台线程中才能使用。

### 事件广播

开发者可以通过 `GlobalEventEmitter` 广播事件，将事件发送给前端。

在下面这个例子中，当用户点击页面时，开发者通过调用 `GlobalEventEmitter` 的 `toggle` 方法来广播事件，实现点击事件由组件 `ComponentA` 传播到 `ComponentB`。

**示例 7:**

**下面是一个示例: event**

**Entry:** `src/event_emitter_toggle`
**Bundle:** `dist/event_emitter_toggle.lynx.bundle` | Web: `dist/event_emitter_toggle.web.bundle`

```tsx {8-10,22-24,44}
import { root, useState } from "@lynx-js/react";
import { useLynxGlobalEventListener } from "@lynx-js/react";
import type { TouchEvent } from "@lynx-js/types";

export function ComponentA() {
  const [eventLog, setEventlog] = useState<string>("");

  useLynxGlobalEventListener("tapitem", (e) => {
    setEventlog((e as TouchEvent).target.dataset.item);
  });

  return (
    <view style={{ width: "100%", height: "100%", justifyContent: "center", alignItems: "center" }}>
      <text>
        Tap on item-<text style={{ color: "red" }}>{eventLog}</text>
      </text>
    </view>
  );
}

export function ComponentB() {
  function handleTap(e: TouchEvent) {
    lynx.getJSModule("GlobalEventEmitter").toggle("tapitem", e);
  }

  return (
    <scroll-view
      scroll-orientation="vertical"
      style={{ width: "100%", height: "calc(100% - 40px)", marginTop: "40px" }}
    >
      {[0, 1, 2, 3, 4, 5, 6].map((item) => {
        return (
          <view
            style={{
              width: "calc(100% - 10px)",
              height: "200px",
              margin: "5px",
              backgroundColor: "orange",
              borderRadius: "5px",
              justifyContent: "center",
              alignItems: "center",
            }}
            data-item={item + 1}
            bindtap={handleTap}
          >
            <text user-interaction-enabled={false}>item-{item + 1}</text>
          </view>
        );
      })}
    </scroll-view>
  );
}

export default function App() {
  return (
    <view style={{ width: "100%", height: "90%" }}>
      <view
        style={{ width: "100%", height: "150px", backgroundColor: "yellow" }}
      >
        <view style={{ position: "absolute" }}>
          <text style={{ color: "blue" }}>ComponentA</text>
        </view>
        <ComponentA />
      </view>
      <view
        style={{
          width: "100%",
          height: "calc(100% - 165px)",
          marginTop: "15px",
          backgroundColor: "#ccc",
        }}
      >
        <view style={{ position: "absolute" }}>
          <text style={{ color: "blue" }}>ComponentB</text>
        </view>
        <ComponentB />
      </view>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```



对于客户端，示例如下：

iOSAndroidHarmonyOS```objective-c
// 可以调用 LynxContext 的 sendGlobalEvent 函数
// 第一个参数为前端监听的事件名称，第二个参数为前端接收到的数据
[LynxContext sendGlobalEvent:@"eventName" withParams:args];
// 或者调用 LynxView 的 sendGlobalEvent 函数
[LynxView sendGlobalEvent:@"eventName" withParams:args];
```
```java
// 可以调用 LynxContext 的 sendGlobalEvent 函数
// 第一个参数为前端监听的事件名称，第二个参数为前端接收到的数据
LynxContext.sendGlobalEvent("eventName", args);
// 或者调用 LynxView 的sendGlobalEvent 函数
LynxView.sendGlobalEvent("eventName", args);
```
```js
// 可以调用 LynxContext 的 sendGlobalEvent 函数
// 第一个参数为前端监听的事件名称，第二个参数为前端接收到的数据
LynxContext.sendGlobalEvent('eventName', args);
```
## 


### 事件订阅

开发者也可以通过 `GlobalEventEmitter` 的 `addListener` 方法来订阅事件，接收来自于前端、客户端的事件。

在下面这个例子中，用户可以接收到 Lynx 发送的 [`onWindowResize`](/zh/api/lynx-api/event/global-event.md#onwindowresize) 事件，该事件在 Lynx 页面大小变化时触发。

**示例 8:**

**下面是一个示例: event**

**Entry:** `src/event_emitter_listen`
**Bundle:** `dist/event_emitter_listen.lynx.bundle` | Web: `dist/event_emitter_listen.web.bundle`

```tsx {6-8}
import { root, useState } from "@lynx-js/react";
import { useLynxGlobalEventListener } from "@lynx-js/react";

export default function App() {
  const [eventLog, setEventLog] = useState<string>("");
  useLynxGlobalEventListener("onWindowResize", (e) => {
    setEventLog("" + e);
  });

  return (
    <view
      style={{
        width: "100%",
        height: "100%",
        borderWidth: "1px",
        borderColor: "red",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <text>Listen onWindowResize Event:</text>
      <text>
        LynxView's width has changed to: <text style={{ color: "red" }}>{eventLog}</text>
      </text>
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```


