webarkit / ARnft

A small javascript library for WebAR with NFT
GNU Lesser General Public License v3.0
220 stars 54 forks source link

Improving event listeners in ARnft class and other classes #213

Open kalwalt opened 3 years ago

kalwalt commented 3 years ago

@albjeremias I would collect here infos about this topic from discussion #208 #206 #189 To summarize it is possible to extends the ARnft class with the EventEmitter class:

export default class ARnft extends EventEmitter

see comment https://github.com/webarkit/ARnft/pull/208#issuecomment-936757805 linked article: https://javascript.plainenglish.io/how-we-can-use-node-js-event-emitter-5c9e39c38749

I found that there is also a typed package to help with the Typescript language tiny-typed-emitter read this stackoverflow article

Other useful resources: https://javascript.info/bubbling-and-capturing

kalwalt commented 3 years ago

I have opted for another solution: I created a target property inherited to the EventTarget (MDN ref: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) and the target is attached to the Window or Global object:

 private target: EventTarget;
 // In the constructor...
 this.target = window || global;
 // Then you can use your target as always...
 this.target.dispatchEvent(initEvent);

I will link the upcoming PR with more details.

kalwalt commented 3 years ago

We should make other improvements in this field. We should create an Event base class and then extends to an DataEvent class, so we can do:

this.target.dispatchEvent(new DataEvent(ARnftEvent.ARNFT_DISPLAY_EVENT, data));

where ARnftEvent.ARNFT_DISPLAY_EVENT = 'Display_event'

data = { message: "hello" } but is injected in {detail: data} without to wite this part. Note this is a pseudo code! I will elaborate this idea in the issue when i have time.