Skip to the content.

jFactory > Reference > Traits > TraitEvents

TraitEvents

Registry / Methods

Registers DOM Event Listeners and Component Event Observers that will be removed at Remove Phase.


Note: TraitEvents is based on JFactoryEvents that redirects to jQuery Events wich supports advanced features like Event Namespaces and Event Delegation. ***

Registry

myComponent.$.listeners for DOM Events
myComponent.$.observers for Component Events

Injected Methods

$on(events [, targetSelector [, delegateSelector]], handler)

$off([events, [target [, selector]] [, handler]])

$trigger(events [, target] [, data]) {

Returns Promise

Calls the handlers registered by the component for each event passed in events.

Trigger is awaitable, see Queued vs Parallel execution

Queued vs Parallel execution

By default jFactory runs asynchronous handlers in the order of the queue, waiting for each one to resolve before launching the next one.
You can also run all handlers asynchronously in parallel using $triggerParallel() (not recommended because it’s the best way to introduce race conditions):

myComponent.$on("myEvent", async (event, data  => {wait(100).then(console.log(1))})
myComponent.$on("myEvent", async (event, data) => {wait(1).then(console.log(2))})

await myComponent.$trigger("myEvent")
console.log(3)
// outputs 1,2,3 (queued) 

await myComponent.$triggerParallel("myEvent")
console.log(3)
// outputs 2,1,3 (Parallelized)

Event Namespaces

An Event Namespace is a Group Name you can associate with events:

myComponent.$on("click.myNamespace", ...)
myComponent.$on("keydown.myNamespace keyup.myNamespace", ...)
myComponent.$on("myEvent.myNamespace", ...)

This can be used to unsubscribe an entire group:

myComponent.$off(".myNamespace")

You can attach multiple namespaces on an event but it doesn’t form a path, the declaration order has no effect:

myComponent.$on("click.myNamespace1.myNamespace2", handler1)
myComponent.$on("click.myNamespace2.myNamespace1", handler2)

myComponent.$off(".myNamespace2") // the two handlers are removed  

See also jQuery Events

Event Delegation

“Event delegation allows you to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.” – learn.jquery.com

// Without event delegation:
// puts a listener on all elements matching $(".menu-button")
myComponent.$on("pointerdown", ".menu-button", event => {})

// With event delegation:
// puts a single listener on $("#container") which will react 
// at runtime if the event target match $("#container .menu-button")  
myComponent.$on("pointerdown", "#container", ".menu-button", event => {})