mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-10 12:46:15 -08:00
docs(core): [SITE-04] document event payloads and synchronous dispatch
This commit is contained in:
1 parent
0a060e6088
commit
8d2ec199d7
96 files changed
+5823
-2965
No files matched your search
@@ -69,6 +69,104 @@ art.on('ready', onReady);
|
||||
|
||||
:::
|
||||
|
||||
## 订阅与同步派发 {#emitter-contract}
|
||||
|
||||
播放器继承 `Artplayer.Emitter`。`on(name, callback, ctx?)`、`once`、`off`、`emit(name, ...args)` 都返回当前实例;它们不是 DOM addEventListener,也不是返回 Promise 的消息队列。
|
||||
|
||||
- on 按注册顺序保存监听器,重复注册同一函数会重复调用。ctx 原样作为普通函数的 this;未传时以 undefined 调用,不自动绑定播放器,箭头函数仍使用词法 this。
|
||||
- emit 同步遍历派发开始时的监听器快照。过程中新增的监听器不参加这次派发;移除的普通监听器若已在快照里,仍会执行。回调参数按原引用传递,回调返回值被忽略。
|
||||
- once 在调用用户回调前移除,并防止嵌套派发重复消费同一注册;即使回调抛错也已消费。off(name, callback) 移除该函数的全部普通/once注册,不按ctx区分;off(name) 移除该名称的全部监听器。
|
||||
- 回调同步抛错会终止当次后续监听器并沿调用栈传播;async回调的Promise不被等待,调用者应处理异步失败。error只是普通事件名,不具备Node EventEmitter的特殊错误规则。
|
||||
- e是延迟创建的监听器表,保存fn和ctx,属于可见的历史接口;新建独立Emitter时可能不存在。用on/off维护订阅,不直接修改这个内部表。数字名称与对应字符串共享对象key,Symbol是独立key;根播放器类型的旧名称重载更窄,准确入口/独立泛型Emitter可表达更多名称。
|
||||
|
||||
手动emit只发通知,不替代播放器方法;伪造内置事件还可能触发核心内部监听器。销毁会清理核心拥有的DOM/内部订阅,但不等于清空用户事件表;用户保留实例时仍应移除不再需要的订阅。与DOM事件资源管理器 `art.events` 的区别见高级属性指南。
|
||||
|
||||
## 原生事件转发 {#native-event-contract}
|
||||
|
||||
以下默认媒体事件以 `video:` 为前缀转发,参数是原始Event对象,浏览器/代理决定它们何时发生:
|
||||
|
||||
`abort`、`canplay`、`canplaythrough`、`durationchange`、`emptied`、`ended`、`error`、`loadeddata`、`loadedmetadata`、`loadstart`、`pause`、`play`、`playing`、`progress`、`ratechange`、`seeked`、`seeking`、`stalled`、`suspend`、`timeupdate`、`volumechange`、`waiting`。
|
||||
|
||||
`video:error` 的参数不是MediaError或Error实例;需要时读取 `art.video.error`。旧类型保留 `video:complete` 和 `video:encrypted`,但默认config.events没有这两个名称,核心不会自动转发。若适配器需要扩展,须自行建立转发或在实例构造前配置事件清单;类型中有名称不证明运行时会发出事件。
|
||||
|
||||
全局转发来自播放器当前绑定的document/window,每次携带原始Event:
|
||||
|
||||
| 前缀 | 默认名称 |
|
||||
| --- | --- |
|
||||
| `document:` | click、mouseup、keydown、touchend、touchcancel、touchmove、mousemove、pointerup、contextmenu、pointermove、visibilitychange、webkitfullscreenchange |
|
||||
| `window:` | resize、scroll、orientationchange |
|
||||
|
||||
它们不是仅在播放器内触发;可通过events.bindGlobalEvents重绑定到所属窗口。销毁后停止原生转发。document:keydown等参数实际保留KeyboardEvent/MouseEvent的原生子类型;转发不保证某个浏览器会产生每一种事件。
|
||||
|
||||
## 自定义事件参数与阶段 {#custom-event-contract}
|
||||
|
||||
内置监听器与用户监听器共用同步派发机制;构造时先注册的内部监听器可在原生转发过程中先发出自定义事件。不能为所有代理/浏览器规定统一的跨事件总顺序。
|
||||
|
||||
### 媒体与生命周期
|
||||
|
||||
| 事件 | 参数与实际阶段 |
|
||||
| --- | --- |
|
||||
| `ready` | 无参数;首个处理成功的video:canplay中设置isReady后发出一次,不等待异步插件、字幕或第三方SDK |
|
||||
| `restart` | 本次提交的URL;已有URL且实例ready后,实际媒体地址发生变化的当前切源操作在canplay时发出。不保证相同URL赋值会发出 |
|
||||
| `play` | 无参数;art.play等待媒体play成功后,在操作仍有效时发出。直接video.play不自动产生这个自定义事件;原生video:play仍可发出 |
|
||||
| `pause` | 无参数;art.pause调用媒体pause并更新提示后同步发出,即使媒体原本已暂停。与video:pause不是同一事件 |
|
||||
| `destroy` | 无参数;原生监听/资源和模板清理、实例登记移除及isDestroy置true后发出。不要假定回调中DOM仍挂载;destroy(false)另行控制保留DOM |
|
||||
| `error` | 原始错误值、当前重试次数;重连等待后提交重试时发出,不是每次原生错误或所有异步失败的统一通道 |
|
||||
| `seek` | 赋值后的currentTime、原始请求时间(可为数字或字符串);不是原生seeked完成通知 |
|
||||
| `muted` | 传给art.muted的布尔值;重复赋值仍可触发。直接改video.muted以原生video:volumechange观察 |
|
||||
| `screenshot` | PNG data URI;截图方法得到图像并尝试触发下载后发出,不证明文件已保存。getDataURL/getBlobUrl本身不发此事件 |
|
||||
| `airplay` | 无参数;可用的原生选择器调用后发出,不表示远端已连接或开始播放 |
|
||||
| `raf` | 无参数;构造前USE_RAF启用时,播放中的帧循环发出,不是视频解码帧回调 |
|
||||
|
||||
### 界面与输入
|
||||
|
||||
| 事件 | 参数与实际阶段 |
|
||||
| --- | --- |
|
||||
| `info`、`layer`、`loading`、`mask`、`subtitle`、`contextmenu`、`control`、`setting` | show设置的布尔值;重复设置相同值也可触发,不是动画完成事件 |
|
||||
| `focus` / `blur` | document click/contextmenu的原始事件,按路径是否包含播放器区分;不是DOM focus/blur事件,状态不变时也可发出 |
|
||||
| `click` / `dblclick` | 视频节点点击事件;双击由DBCLICK_TIME窗口内计数得到,第一次click已立即发出,之后才执行播放/全屏动作 |
|
||||
| `hover` | 是否进入、原始mouseenter/mouseleave事件 |
|
||||
| `mousemove` | 播放器节点的MouseEvent,不是节流后的document坐标 |
|
||||
| `hotkey` | KeyboardEvent;匹配的快捷键回调执行后发出,受焦点/输入过滤约束 |
|
||||
| `keydown` | KeyboardEvent;桌面快捷键分发之后仍可发出,即使没有匹配键或播放器未聚焦;移动端不会自动安装这条快捷键分发。需要原始全局事件用document:keydown |
|
||||
| `resize` | 无参数;窗口防抖、元数据/显示模式/主动布局等路径会发出,不只来自window:resize |
|
||||
| `view` | 是否与视口相交;经滚动leading节流,不是元素完全可见或遮挡检测 |
|
||||
| `lock` | 锁定布尔值;内置锁插件更新状态后发出,不是直接赋值isLock的观察器 |
|
||||
| `setBar` | 类型、比例、可选原始鼠标/触摸事件。内置类型loaded/played/hover;程序刷新和键盘路径可能没有第三参数。它是进度UI更新协议,不是播放完成通知 |
|
||||
|
||||
### 尺寸、显示与字幕
|
||||
|
||||
| 事件 | 参数与实际阶段 |
|
||||
| --- | --- |
|
||||
| `aspectRatio` / `flip` | setter规范空值后的字符串;不保证它一定来自内置选择列表 |
|
||||
| `autoHeight` / `autoSize` | 高度数值 / {width, height};有效媒体尺寸下应用布局后发出,无法计算时不发 |
|
||||
| `fullscreen` / `fullscreenWeb` / `mini` / `pip` | 状态布尔值;对应显示adapter观察或完成转换时发出。重复赋值是否发出依模式而异,不是请求成功的通用Promise替代品 |
|
||||
| `fullscreenError` | 所属原生全屏错误事件/adapter提供的值;请求Promise拒绝也可能只进入提示,不能依赖它收集所有全屏失败 |
|
||||
| `subtitleOffset` | 原始请求偏移;实际存储值会限制到[-10,10],没有cue时不发 |
|
||||
| `subtitleBeforeUpdate` / `subtitleAfterUpdate` | cue数组,不是单个cue;渲染前/后同步通知,没有活动cue时两者都不发 |
|
||||
| `subtitleLoad` | 当前cue数组、字幕管理器当前选项(可能为null);原生track加载完成,不是switch Promise的别名 |
|
||||
|
||||
## TypeScript事件视图 {#event-types}
|
||||
|
||||
根入口保留历史事件声明及自定义扩展:例如video:error旧写为Error,字幕更新旧写为单个VTTCue。根入口另有SubtitleUpdateEvents数组重载;需要稳定的准确上下文推导时使用 `artplayer/runtime`,其中原生媒体参数为Event、字幕为SubtitleCue数组、error/fullscreenError为unknown、seek第二参数允许字符串。未知自定义事件保留unknown数组,并不会校验运行时载荷。通用Emitter可以显式指定自己的事件tuple:
|
||||
|
||||
```ts
|
||||
import Artplayer from 'artplayer/runtime';
|
||||
import type { Events, SubtitleCue } from 'artplayer/runtime';
|
||||
|
||||
const bus = new Artplayer.Emitter<{ progress: [value: number] }>();
|
||||
const context = { total: 0 };
|
||||
bus.on('progress', function (value) { this.total += value; }, context);
|
||||
bus.emit('progress', 2);
|
||||
|
||||
const art = new Artplayer({ container: '.artplayer-app', url: '/assets/sample/video.mp4' });
|
||||
art.on('video:error', (event: Event) => console.info(event.type));
|
||||
art.on('subtitleBeforeUpdate', (cues: SubtitleCue[]) => console.info(cues.length));
|
||||
const seekArgs: Events['seek'] = [0, '0'];
|
||||
void seekArgs;
|
||||
```
|
||||
|
||||
|
||||
## `ready`
|
||||
|
||||
当播放器首次可以播放器时触发
|
||||
@@ -821,7 +919,7 @@ art.on('keydown', (event) => {
|
||||
|
||||
## `video:complete`
|
||||
|
||||
OfflineAudioContext 渲染完成
|
||||
历史类型保留的名称,默认视频事件清单不转发此事件。视频播放结束使用 `video:ended`。
|
||||
|
||||
## `video:durationchange`
|
||||
|
||||
|
||||
@@ -69,6 +69,104 @@ art.on('ready', onReady);
|
||||
|
||||
:::
|
||||
|
||||
## Subscription and synchronous dispatch {#emitter-contract}
|
||||
|
||||
Players inherit `Artplayer.Emitter`. `on(name, callback, ctx?)`, `once`, `off`, and `emit(name, ...args)` all return the current instance. They are neither DOM addEventListener nor a Promise-based message queue.
|
||||
|
||||
- on keeps registration order. Registering the same function twice invokes it twice. ctx is passed unchanged as an ordinary function's this; omission means undefined, not an automatic player binding. Arrows retain their lexical this.
|
||||
- emit synchronously walks a snapshot taken at dispatch start. Added listeners wait until a later dispatch; removed ordinary listeners already in the snapshot still run. Arguments retain their references; callback return values are ignored.
|
||||
- once removes itself before invoking the callback and prevents nested dispatch from consuming the same registration twice, even if the callback throws. off(name, callback) removes all ordinary/once registrations for that function regardless of ctx; off(name) removes every listener for the name.
|
||||
- A synchronous throw stops subsequent listeners in that dispatch and propagates through the call stack. Async callbacks are not awaited; handle their failures yourself. The name error has no special Node EventEmitter behavior.
|
||||
- e is the lazily created registry of fn/ctx records and remains a visible historical interface. A fresh standalone Emitter may not have it yet. Use on/off rather than editing the table. Numeric keys share their string-equivalent channel; symbols have separate keys. The root player's historical overloads accept narrower names than the accurate entry or a generic Emitter.
|
||||
|
||||
Manual emit only sends a notification; it does not replace player methods. Emitting built-in names may also trigger internal listeners. Destruction releases core-owned DOM/internal subscriptions but does not clear every user registration; remove unwanted subscriptions if you retain the instance. The advanced-properties guide explains the separate DOM listener manager, art.events.
|
||||
|
||||
## Native forwarding {#native-event-contract}
|
||||
|
||||
The default media events below are forwarded with a `video:` prefix and the original Event object. The browser or proxy determines when they occur:
|
||||
|
||||
`abort`, `canplay`, `canplaythrough`, `durationchange`, `emptied`, `ended`, `error`, `loadeddata`, `loadedmetadata`, `loadstart`, `pause`, `play`, `playing`, `progress`, `ratechange`, `seeked`, `seeking`, `stalled`, `suspend`, `timeupdate`, `volumechange`, `waiting`.
|
||||
|
||||
The `video:error` argument is not a MediaError or Error instance; inspect `art.video.error` when needed. Historical types include `video:complete` and `video:encrypted`, but neither appears in the default config.events, so the core does not automatically forward them. An adapter must provide forwarding or configure the event inventory before construction. A declared name does not prove an event is produced at runtime.
|
||||
|
||||
Global forwarding uses the player's currently bound document/window and passes the original Event:
|
||||
|
||||
| Prefix | Default names |
|
||||
| --- | --- |
|
||||
| `document:` | click, mouseup, keydown, touchend, touchcancel, touchmove, mousemove, pointerup, contextmenu, pointermove, visibilitychange, webkitfullscreenchange |
|
||||
| `window:` | resize, scroll, orientationchange |
|
||||
|
||||
These are not restricted to interactions inside the player. events.bindGlobalEvents can rebind them to the owning window. Destruction stops native forwarding. Arguments preserve native subtypes such as KeyboardEvent/MouseEvent; forwarding does not guarantee that a browser produces every event.
|
||||
|
||||
## Custom payloads and timing {#custom-event-contract}
|
||||
|
||||
Internal and user listeners share synchronous dispatch. Internal listeners registered during construction can emit a custom event before later user listeners receive the native forwarding event. Do not assume one total ordering across all browsers and proxies.
|
||||
|
||||
### Media and lifecycle
|
||||
|
||||
| Event | Payload and actual stage |
|
||||
| --- | --- |
|
||||
| `ready` | No arguments; once in the first successfully handled video:canplay, after isReady is set. Does not wait for async plugins, subtitles, or SDKs |
|
||||
| `restart` | Submitted URL; for a ready player with an existing URL, the active source change emits at canplay when the actual media URL changed. Assigning the same URL need not emit it |
|
||||
| `play` | No arguments; art.play emits after the media play call succeeds while its operation remains current. Direct video.play does not generate this custom event, though native video:play can occur |
|
||||
| `pause` | No arguments; art.pause emits synchronously after calling media pause and updating the notice, even if already paused. Separate from video:pause |
|
||||
| `destroy` | No arguments; after native resources/template cleanup, instance removal, and setting isDestroy true. Do not assume mounted DOM inside the callback; destroy(false) separately preserves DOM |
|
||||
| `error` | Original error value and retry count; emitted when reconnection submits a retry after waiting, not on every native error or every async failure |
|
||||
| `seek` | currentTime after assignment and the original requested time (number or string), not native seeked completion |
|
||||
| `muted` | Boolean supplied to art.muted, including repeated assignments. Observe video:volumechange for direct video.muted changes |
|
||||
| `screenshot` | PNG data URI after image capture and an attempted download, not proof a file was saved. getDataURL/getBlobUrl alone do not emit it |
|
||||
| `airplay` | No arguments; after invoking an available native picker, not confirmation of remote connection or playback |
|
||||
| `raf` | No arguments; emitted during playback when USE_RAF was enabled before construction. Not a decoded-video-frame callback |
|
||||
|
||||
### UI and input
|
||||
|
||||
| Event | Payload and actual stage |
|
||||
| --- | --- |
|
||||
| `info`, `layer`, `loading`, `mask`, `subtitle`, `contextmenu`, `control`, `setting` | Boolean assigned to show; repeated identical assignments can emit again. Not animation completion |
|
||||
| `focus` / `blur` | Original document click/contextmenu event, classified by whether its path includes the player. Not DOM focus/blur; can emit even without a state change |
|
||||
| `click` / `dblclick` | Video click event. Double-click is counted within DBCLICK_TIME; the first click emits immediately, before playback/fullscreen actions |
|
||||
| `hover` | Enter/leave boolean and original mouseenter/mouseleave event |
|
||||
| `mousemove` | MouseEvent from the player node, not throttled document coordinates |
|
||||
| `hotkey` | KeyboardEvent after matching shortcut callbacks, subject to focus/input filtering |
|
||||
| `keydown` | KeyboardEvent after desktop shortcut dispatch, even without a matching key or player focus. Mobile does not automatically install this shortcut dispatcher; use document:keydown for the raw global event |
|
||||
| `resize` | No arguments; window debounce, metadata, display-mode changes, or explicit layout paths, not just window:resize |
|
||||
| `view` | Viewport-intersection boolean after leading scroll throttling, not complete visibility or occlusion detection |
|
||||
| `lock` | Boolean after the built-in lock plugin updates state, not an observer of direct isLock assignment |
|
||||
| `setBar` | Type, fraction, and optional original mouse/touch event. Built-in types are loaded/played/hover; programmatic and keyboard updates may omit the third argument. A progress UI protocol, not playback completion |
|
||||
|
||||
### Size, display, and subtitles
|
||||
|
||||
| Event | Payload and actual stage |
|
||||
| --- | --- |
|
||||
| `aspectRatio` / `flip` | String after the setter normalizes an empty value; not necessarily a member of the built-in selector list |
|
||||
| `autoHeight` / `autoSize` | Height number / {width, height} after valid media dimensions allow layout. No event when calculation is unavailable |
|
||||
| `fullscreen` / `fullscreenWeb` / `mini` / `pip` | Boolean from the display adapter's observation or transition. Duplicate-assignment behavior varies by mode; not a universal replacement for request completion |
|
||||
| `fullscreenError` | Owned native fullscreen error event/adapter value. A request Promise rejection may instead only update the notice; this does not collect every fullscreen failure |
|
||||
| `subtitleOffset` | Original requested offset; stored offset clamps to[-10,10]. No event without cues |
|
||||
| `subtitleBeforeUpdate` / `subtitleAfterUpdate` | Cue arrays, not individual cues, synchronously before/after rendering. Neither emits without active cues |
|
||||
| `subtitleLoad` | Current cue array and the subtitle manager's current options (possibly null), after native track load. Not an alias for switch fulfillment |
|
||||
|
||||
## TypeScript event views {#event-types}
|
||||
|
||||
The root entry retains historical declarations and custom augmentation: video:error was typed as Error and subtitle updates as one VTTCue. It also has array overloads through SubtitleUpdateEvents. Use `artplayer/runtime` for accurate contextual inference: Event for native media payloads, SubtitleCue arrays for updates, unknown for error/fullscreenError, and a string-capable second seek argument. Unknown custom events retain unknown arrays without runtime payload validation. A generic Emitter can declare its own event tuples:
|
||||
|
||||
```ts
|
||||
import Artplayer from 'artplayer/runtime';
|
||||
import type { Events, SubtitleCue } from 'artplayer/runtime';
|
||||
|
||||
const bus = new Artplayer.Emitter<{ progress: [value: number] }>();
|
||||
const context = { total: 0 };
|
||||
bus.on('progress', function (value) { this.total += value; }, context);
|
||||
bus.emit('progress', 2);
|
||||
|
||||
const art = new Artplayer({ container: '.artplayer-app', url: '/assets/sample/video.mp4' });
|
||||
art.on('video:error', (event: Event) => console.info(event.type));
|
||||
art.on('subtitleBeforeUpdate', (cues: SubtitleCue[]) => console.info(cues.length));
|
||||
const seekArgs: Events['seek'] = [0, '0'];
|
||||
void seekArgs;
|
||||
```
|
||||
|
||||
|
||||
## `ready`
|
||||
|
||||
Triggered when the player is ready for the first time.
|
||||
@@ -824,7 +922,7 @@ The browser estimates it can play the media through to the end without stopping
|
||||
|
||||
## `video:complete`
|
||||
|
||||
The OfflineAudioContext rendering is complete.
|
||||
Historical declared name; not forwarded by the default video event inventory. Use `video:ended` for media reaching its end.
|
||||
|
||||
## `video:durationchange`
|
||||
|
||||
|
||||
Reference in new issue
Block a user