From 07c29abbec08707e814f5170d18caa9752f5ed6e Mon Sep 17 00:00:00 2001 From: Yohan Boniface Date: Fri, 10 Jan 2025 16:18:10 +0100 Subject: [PATCH] chore(utils): use native events instead of array of callbacks for WithEvents Co-authored-by: David Larlet --- umap/static/umap/js/modules/data/layer.js | 4 ++-- umap/static/umap/js/modules/form/fields.js | 2 +- umap/static/umap/js/modules/utils.js | 17 +++++------------ 3 files changed, 8 insertions(+), 15 deletions(-) diff --git a/umap/static/umap/js/modules/data/layer.js b/umap/static/umap/js/modules/data/layer.js index e35e51b16..c53d91632 100644 --- a/umap/static/umap/js/modules/data/layer.js +++ b/umap/static/umap/js/modules/data/layer.js @@ -668,9 +668,9 @@ export class DataLayer extends ServerStored { ] DomUtil.createTitle(container, translate('Layer properties'), 'icon-layers') let builder = new MutatingForm(this, metadataFields) - builder.on('set', (helper) => { + builder.on('set', ({ detail }) => { this._umap.onDataLayersChanged() - if (helper.field === 'options.type') { + if (detail.helper.field === 'options.type') { this.edit() } }) diff --git a/umap/static/umap/js/modules/form/fields.js b/umap/static/umap/js/modules/form/fields.js index a74de302e..1ff8b5b0a 100644 --- a/umap/static/umap/js/modules/form/fields.js +++ b/umap/static/umap/js/modules/form/fields.js @@ -97,7 +97,7 @@ class BaseElement { sync() { this.set() - this.builder.fire('set', this) + this.builder.fire('set', { helper: this }) } set() { diff --git a/umap/static/umap/js/modules/utils.js b/umap/static/umap/js/modules/utils.js index b705f2c09..b36bc8402 100644 --- a/umap/static/umap/js/modules/utils.js +++ b/umap/static/umap/js/modules/utils.js @@ -451,24 +451,17 @@ export function eachElement(selector, callback) { export class WithEvents { constructor() { - this._callbacks = {} + this._target = new EventTarget() } on(eventType, callback) { if (typeof callback !== 'function') return - if (this._callbacks[eventType] === undefined) { - this._callbacks[eventType] = [] - } - - this._callbacks[eventType].push(callback) + this._target.addEventListener(eventType, callback) } - fire(eventType, ...args) { - if (this._callbacks[eventType] === undefined) return - - for (const callback of this._callbacks[eventType]) { - callback(...args) - } + fire(eventType, detail) { + const event = new CustomEvent(eventType, { detail }) + this._target.dispatchEvent(event) } }