Fire event with this.emit(...)? #1454
Replies: 4 comments
-
Posted at 2021-03-27 by AndreyVS Hm.. For whatever reason, it works now.. I'm a bit embarrassed.. Just for reference, code is here:
|
Beta Was this translation helpful? Give feedback.
-
Posted at 2021-03-27 by Robin Sat 2021.03.27 @AndreyVS While searching for an answer to #1, our posts crossed:
I'm now puzzled also, as: ref: 'You cannot rebind this in an arrow function.' violates ECMAScript specification:
It seems the L3 ()=>this.emit('TestEvent') arrow function is bound to the setTiemout() object, or maybe *this* is bound to the application environment Global scope and not the L2 aClass.prototype.testEmit object as desired. This might explain why it just works, and not actually a specification violation.
Incidentatlly, Post #2 L1 should not terminate with a semi-colon, and L4 should. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2021-03-27 by Robin
After playing with these snippets, I'm now not entirely sure what the original intent is/was. In post #2 L6, registers an arrow function response to object a Missing, following L8 is the event listener registration for object a1 So when L9 executes, there isn't the registered listener to respond to the console. > 'Thus if e.g. I have two step up modules, I cannot subscribe directly to each of them' It is possible that as the second 'Got event' never occurs, (comment L9) compared to the test results in post #1 is just simply tripping up thinking, as there isn't a means (an on() method attached to a1) to view the second event? |
Beta Was this translation helpful? Give feedback.
-
Posted at 2021-03-28 by AndreyVS Many thanks, Robin! However, seems that this correctly references the instance, also supported by stackoverflow answer:
We can see if we print it out:
By contrast, if we replace arrow function in L6 with function(), this will reference the global object, which does not have emit(), and code crashes.
To summarize for reference, this can be used, but should be cautious when calling setTimeout:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Posted at 2021-03-26 by AndreyVS
Hi Everyone! On Puck I try to organize communication between objects with events (see Object.emit and discussion here). However, I cannot emit an event within a prototype function with 'this'. Thus if e.g. I have two step up modules, I cannot subscribe directly to each of them, and need to add either a module id as an event argument or additional empty object (see below).
In comments here is what I'd want:
Here is a way round with an empty object:
Why can't I use this.emit(...)?
Beta Was this translation helpful? Give feedback.
All reactions