Bonjour,
je me suis fais une classe avec 2 methodes : .on(...) et .dispatch(...) afin de simuler un event sur mon object
(et un moment dans ma class, j'ai un this.dispatch('dataLoaded') )
Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
1
2 cons toto = new MaClass(); toto.on('dataLoaded', () => { console.log('ok'); });
avant, je passais par des custom events du document
Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11 on(key, callback, options) { this._dispatchHandlers[key] = { callback, options }; } dispatch(key, datas={}) { if(this._dispatchHandlers[key]) { this._dispatchHandlers[key].callback(datas); if(this._dispatchHandlers[key].options && this._dispatchHandlers[key].options.once === true) { delete this._dispatchHandlers[key]; } } }
Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6 on(key, callback, options) { document.addEventListener(key, callback, options); } _dispatch(key, datas= {}) { document.dispatchEvent(new CustomEvent(key, { detail: data })); }
est-il preferable de passer par une methode en particulier ? (pourquoi ?)
Partager