2019-05-11 12:11:00 +02:00
|
|
|
# 🦉 Utils 🦉
|
2019-05-10 20:50:14 +02:00
|
|
|
|
|
|
|
|
Owl export a few useful utility functions, to help with common issues. Those
|
|
|
|
|
functions are all available in the `owl.utils` namespace.
|
|
|
|
|
|
|
|
|
|
## Content
|
|
|
|
|
|
2019-06-11 08:58:37 +02:00
|
|
|
- [`whenReady`](#whenready): executing code when DOM is ready
|
2019-10-17 12:20:22 +02:00
|
|
|
- [`loadFile`](#loadfile): loading a file (useful for templates)
|
2022-01-13 10:26:14 +01:00
|
|
|
- [`EventBus`](#eventbus): a simple EventBus
|
2019-10-17 09:50:03 +02:00
|
|
|
|
2019-05-10 20:50:14 +02:00
|
|
|
## `whenReady`
|
|
|
|
|
|
2019-06-11 13:36:59 +02:00
|
|
|
The function `whenReady` returns a `Promise` resolved when the DOM is ready (if
|
|
|
|
|
not ready yet, resolved directly otherwise). If called with a callback as
|
|
|
|
|
argument, it executes it as soon as the DOM ready (or directly).
|
|
|
|
|
|
|
|
|
|
```js
|
2022-01-13 10:26:14 +01:00
|
|
|
const { whenReady } = owl;
|
|
|
|
|
|
|
|
|
|
await whenReady();
|
|
|
|
|
// do something
|
2019-06-11 13:36:59 +02:00
|
|
|
```
|
2019-05-10 20:50:14 +02:00
|
|
|
|
2019-10-17 09:50:03 +02:00
|
|
|
or alternatively:
|
|
|
|
|
|
2019-05-10 20:50:14 +02:00
|
|
|
```js
|
2022-01-13 10:26:14 +01:00
|
|
|
whenReady(function () {
|
|
|
|
|
// do something
|
2019-05-10 20:50:14 +02:00
|
|
|
});
|
|
|
|
|
```
|
|
|
|
|
|
2019-10-17 12:20:22 +02:00
|
|
|
## `loadFile`
|
2019-05-10 20:50:14 +02:00
|
|
|
|
2019-10-20 09:01:38 +02:00
|
|
|
`loadFile` is a helper function to fetch a file. It simply
|
2019-10-17 12:20:22 +02:00
|
|
|
performs a `GET` request and returns the resulting string in a promise. The
|
|
|
|
|
initial usecase for this function is to load a template file. For example:
|
2019-10-17 09:50:03 +02:00
|
|
|
|
2019-06-11 08:58:37 +02:00
|
|
|
```js
|
2022-01-13 10:26:14 +01:00
|
|
|
const { loadFile } = owl;
|
2019-10-17 09:50:03 +02:00
|
|
|
|
2022-01-13 10:26:14 +01:00
|
|
|
async function makeEnv() {
|
|
|
|
|
const templates = await loadFile("templates.xml");
|
|
|
|
|
// do something
|
2019-10-17 09:50:03 +02:00
|
|
|
}
|
|
|
|
|
```
|
2019-10-20 09:01:38 +02:00
|
|
|
|
2022-01-13 10:26:14 +01:00
|
|
|
## `EventBus`
|
2019-10-17 09:50:03 +02:00
|
|
|
|
2022-01-13 10:26:14 +01:00
|
|
|
It is a simple `EventBus`, with the same API as usual DOM elements, and an
|
|
|
|
|
additional `trigger` method to dispatch events:
|
2019-10-17 09:50:03 +02:00
|
|
|
|
|
|
|
|
```js
|
2022-01-13 10:26:14 +01:00
|
|
|
const bus = new EventBus();
|
|
|
|
|
bus.addEventListener("event", () => console.log("something happened"));
|
2019-10-17 09:50:03 +02:00
|
|
|
|
2022-01-13 10:26:14 +01:00
|
|
|
bus.trigger("event"); // 'something happened' is logged
|
2019-10-20 09:01:38 +02:00
|
|
|
```
|