Reputation: 971
In Aurelia, binding events to methods is done either via trigger
or delegate
. There's quite a good explanation in the docs on which one to use:
http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-delegate-vs-trigger/1
However, the docs does not mention CustomEvent
. What is the guidelines in case of CustomEvent
?
Upvotes: 1
Views: 2325
Reputation: 1964
Sorry I cannot comment, balazska's answer is great but it assumes you understand clearly how everything in event works. To simplify his version:
If you listen to custom event on something like this:
<div repeat.for='items of my_1000_items_collection' custom-event.trigger='doIt()'></div>
You are registering 1000 listener entries. In this case, better use delegate and adjust code if needed, it may increase the performance of your application.
You can also use capture
, which is undocumented at the moment.(on it's way to release) Capture Event
<div repeat.for='items of my_1000_items_collection' custom-event.capture='doIt()'></div>
Upvotes: 3
Reputation: 971
It's a bit complicated, because CustomEvent
is quite customizable and can be sent at any point of time.
Aurelia docs says delegate
is preferred. However, the implementation of delegate
relies on a global event handler of <body>
element, so cannot be used always. An element dispatching an event, which then bubbles up to <body>
, to the root of all visibles in the DOM. So in order to make delegate
work:
CustomEvent
dispatchEvent
is being called on) should be attached to the DOM-tree. So that the event actually reaches the <body>
while bubbling.Point 1. is just a matter of settings, so let's see 2. This depends on if the event is being dispatched before or after the viewmodel is being attached to the DOM (before attached()
callback). If before, then delegate
won't work, use trigger
. Otherwise use delegate
.
Happens before attaching to DOM → use trigger
:
canActivate()
, activate()
bind()
, changed callbacks for bindables, xxxChanged()
Happens certainly after attached → use delegate
: basically built-in user-based DOM-events (click, select, change, etc.). Reason: because the user can only interact with our viewmodel, if it is already in the DOM.
Upvotes: 4