From 2eb151c92d71e3ef6441eb8dc488a47f244641a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20Lef=C3=A8vre=20=28lul=29?= Date: Wed, 22 May 2024 10:09:41 +0200 Subject: [PATCH] [IMP] index: export batched utility function 'batched' will be used in odoo/o-spreadsheet. There's also a copied version (slightly modified) in odoo/odoo. It shows it could be useful outside owl. --- doc/readme.md | 1 + doc/reference/utils.md | 20 ++++++++++++++++++++ src/runtime/index.ts | 2 +- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/doc/readme.md b/doc/readme.md index 36fe630f1..9363ba708 100644 --- a/doc/readme.md +++ b/doc/readme.md @@ -47,3 +47,4 @@ Utility/helpers: - [`status`](reference/component.md#status-helper): utility function to get the status of a component (new, mounted or destroyed) - [`validate`](reference/utils.md#validate): validates if an object satisfies a specified schema - [`whenReady`](reference/utils.md#whenready): utility function to execute code when DOM is ready +- [`batched`](reference/utils.md#batched): utility function to batch function calls diff --git a/doc/reference/utils.md b/doc/reference/utils.md index 650769f9b..dba403786 100644 --- a/doc/reference/utils.md +++ b/doc/reference/utils.md @@ -9,6 +9,7 @@ functions are all available in the `owl.utils` namespace. - [`loadFile`](#loadfile): loading a file (useful for templates) - [`EventBus`](#eventbus): a simple EventBus - [`validate`](#validate): a validation function +- [`batched`](#batched): batch function calls ## `whenReady` @@ -78,3 +79,22 @@ validate( // - 'id' is missing (should be a number), // - 'url' is missing (should be a boolean or list of numbers), ``` + +## `batched` + +The `batched` function creates a batched version of a callback so that multiple calls to it within the same microtick will only result in a single invocation of the original callback. + +```js +function hello() { + console.log("hello"); +} + +const batchedHello = batched(hello); +batchedHello(); +// Nothing is logged +batchedHello(); +// Still not logged + +await Promise.resolve(); // Await the next microtick +// "hello" is logged only once +``` diff --git a/src/runtime/index.ts b/src/runtime/index.ts index 651263a9c..10ff0afb4 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -41,7 +41,7 @@ export { useComponent, useState } from "./component_node"; export { status } from "./status"; export { reactive, markRaw, toRaw } from "./reactivity"; export { useEffect, useEnv, useExternalListener, useRef, useChildSubEnv, useSubEnv } from "./hooks"; -export { EventBus, whenReady, loadFile, markup } from "./utils"; +export { batched, EventBus, whenReady, loadFile, markup } from "./utils"; export { onWillStart, onMounted,