dojo dragon main logo

核心渲染中间件

@dojo/framework/core/vdom 模块包含基础中间件,这些中间件在大多数 Dojo 应用程序中都很有用。它们在构建其他自定义中间件时主要有用(它们支撑着框架提供的 其他中间件),但在一般的小部件开发中偶尔也会有用。

invalidator

最重要的中间件,它提供了一个钩子,用于连接小部件的失效生命周期。调用 invalidator() 将在下次计划的渲染期间将小部件排队进行渲染。

API

import { invalidator } from '@dojo/framework/core/vdom';
  • invalidator()
    • 将使用的小部件标记为无效,需要重新渲染。

node

为小部件提供访问其底层 DOM 节点的权限,这些节点由节点 key 标识。当请求有效的 DOM 节点但不可用时,Dojo 将在 DOM 节点可用后立即重新渲染小部件。

API

import { node } from '@dojo/framework/core/vdom';
  • node.get(key: string | number): HTMLElement | null
    • 返回小部件的指定 DOM 元素,由节点的 key 属性标识。如果当前小部件不存在指定的 DOM 元素,则返回 null

diffProperty

允许小部件通过为指定属性注册自己的 diff 函数来对差异检测进行细粒度控制。当尝试重新渲染小部件时,框架将调用该函数,以确定是否进行了需要进行完整重新渲染的任何更改。如果在小部件的属性集中未检测到任何差异,则更新将被跳过,任何现有的 DOM 节点将保持原样。

编写自定义 diff 函数通常与使用 invalidator 中间件相结合,当属性值的差异需要更新小部件的 DOM 节点时,将当前小部件标记为无效。

diffProperty 的另一个用途是能够返回一个值,该值将从小部件属性中获得。从 callback 返回的值用于替换小部件属性上的相应值。

注意: 在组合小部件或中间件的整个生命周期中,只能为给定属性注册一个 diff 函数,之后将忽略后续调用。默认情况下,渲染引擎使用一种算法,该算法对对象和数组进行浅层差异化,忽略函数,并对所有其他属性类型进行相等性检查。设置自定义 diff 函数将覆盖 Dojo 对该属性的默认差异检测策略。

API

import { diffProperty } from '@dojo/framework/core/vdom';
  • diffProperty(propertyName: string, properties: () => WidgetProperties (current: WidgetProperties, next: WidgetProperties) => void | WidgetProperties[propertyName])
    • 注册指定的 diff 函数,该函数用于确定小部件 propertyName 属性的 currentnext 值之间是否存在任何差异。该函数使用 properties 函数来确定可用的属性和回调的类型,包括参数和返回值。

示例

src/customMiddleware.tsx

import { create, diffProperty } from '@dojo/framework/core/vdom';

const factory = create({ diffProperty }).properties<{ foo?: string }>;

export const customMiddleware = factory(({ properties, middleware: { diffProperty } }) => {
	diffProperty('foo', properties, (current, next) => {
		if (!next.foo) {
			return 'default foo';
		}
	});
	// The rest of the custom middleware that defines the API
});

## `destroy`

Assigns a function that is called on widget destruction, allowing any required resource teardown to take place.

**Note:** `destroy()` can only be called once for each composing widget or middleware, after which further calls will be ignored. For advanced scenarios that need to conditionally add handles for execution when a widget is removed, a single destroy function should be registered that can keep track of and iteratively destroy all necessary resources.

**API:**

```ts
import { destroy } from '@dojo/framework/core/vdom';
  • destroy(destroyFunction: () => void)
    • 设置 destroyFunction,该函数将在当前小部件被销毁时调用。设置函数将覆盖以前为小部件设置的任何销毁函数。

getRegistry

通过处理程序接口提供对小部件自己的 Registry 实例以及根应用程序 Registry(如果需要)的访问权限。

注意: 注册表是一个高级概念,通常在编写 Dojo 应用程序时不需要。它主要由框架内部使用,以实现更高级的用户界面功能,例如 Dojo 存储

API

import { getRegistry } from '@dojo/framework/core/vdom';
  • getRegistry(): RegistryHandler | null
    • 返回当前小部件的 RegistryHandler,如果小部件尚未完全初始化,则返回 null

defer

允许小部件暂停和恢复其渲染逻辑;在短路渲染直到满足某些条件时很有用。

API

import { defer } from '@dojo/framework/core/vdom';
  • defer.pause()
    • 暂停当前小部件的进一步渲染,直到另行标记。
  • defer.resume()
    • 恢复小部件渲染。