Binding - Delegate vs Trigger

- Use delegate except when you cannot use delegate. 
- Event delegation is a technique used to improve application performance. 
- It drastically reduces the number of event subscriptions by leveraging the "bubbling" characteristic of most DOM events. 
- With event delegation, handlers are not attached to individual elements. 
- Instead, a single event handler is attached to a top-level node such as the body element. 
- When an event bubbles up to this shared top-level handler the event delegation logic calls the appropriate handler based on the event's target .
- To find out if event delegation can be used with a particular event, google mdn [event name] event. - In fact, preceding any web platform related google search with mdn often returns a high quality result from the Mozilla Developer Network. 
- Once you're on the event's MDN page, check whether the event bubbles. 
- Only events that bubble can be used with Aurelia's delegate binding command. 
- The blur, focus, load and unload events do not bubble so you'll need to use the trigger binding command to subscribe to these events. 

Exceptions to the general guidance above:

- Use trigger on buttons when the following conditions are met:
1. You need to disable the button.
2. The button's content is made up of other elements (as opposed to just text).
3. This will ensure clicks on disabled button's children won't bubble up to the delegate event handler. 4. Use trigger for click in certain iOS use-cases:
iOS does not bubble click events on elements other than a, button, input & select. If you're subscribing to click on a non-input element like a div and are targeting iOS, use the trigger binding command.

Event delegation with

- delegate & trigger can be sometime too late to react to an event. Some other times, events may never reach to your delegate or trigger handlers, this is the case when you interact with content (elements) generated by 3rd party plugins.
- e.g.
<div class='my-plugin-container' click.delegate='onClickPluginContainer()'>
        Content inside here is generated by a plugin
        That will call `event.stopPropagation()` on any click events
</div>
This is where you may need another way to listen to click event, via binding command capture:
<div class='my-plugin-container' click.capture='onClickPluginContainer()'>
        Content inside here is generated by a plugin
        That will call `event.stopPropagation()` on any click events
</div>
- In the 2nd example, onClickPluginContainer() is guaranteed to happen no matter event.stopPropagation() is called or not inside the container.
- capture is not needed normally & may even be confusing as it's not how we normally works with browser events.

Comments

Popular posts from this blog

Fundamentals - App Config & Startup - VIII

Fundamentals - Dependency Injection V

Style vs Css attribute