Why passing $ event in Angular (when dealing with DOM events) is questionable practice
I was reading the Angular 2 documentation where I found :
Passing the $ event is not good practice
Event object injection shows a significant objection to passing an entire DOM event to a method: the component is too aware of the details of the template. It cannot retrieve information without knowing more than it needs to implement HTML. This breaks the separation of concerns between the template (what the user sees) and the component (how the application processes the user data).
For some reason, I can't really get to what he says. There doesn't seem to be any explanation anywhere.
Can anyone explain the exact meaning of this in simpler terms (with an example if possible)?
source to share
Take a look at the examples the docs already provide before and after:
@Component({ selector: 'key-up1', template: ' <input #box (keyup)="onKey($event)"> <p>{{values}}</p> ' }) export class KeyUpComponent_v1 { values = ''; onKey(event: KeyboardEvent) { this.values += (<HTMLInputElement>event.target).value + ' | '; } }
Here the component needs to know that the event has a target, which is the input element that matters. Now v2:
@Component({ selector: 'key-up2', template: ' <input #box (keyup)="onKey(box.value)"> <p>{{values}}</p> ' }) export class KeyUpComponent_v2 { values = ''; onKey(value: string) { this.values += value + ' | '; } }
Here, the template is responsible for extracting the correct value from its own structure, and all the component knows is that it receives a string. Now imagine:
-
You need to change the element
input
toselect
to limit the range of inputs. What should change in each version? Is it just a template, or does the component have to change too? -
You want to test the processing method. How easy is it for each version? Can you just pass in a string, or do you need to create an event with an element of the corresponding structure?
This is what separation of interests really means - how far does change go? How much does each part of your system need to know about the other parts to get going? On Wikipedia , for example:
Of particular importance is the ability to subsequently improve or modify one section of the code without needing to know the details of other sections and without having to modify those sections accordingly.
However, as snorkpete suggests , note that the reservation around passing $event
to bean methods only applies when $event
referring to DOM events. In the case where you use EventEmitter
to create your own events, it will $event
(most likely) be an object from the business domain, and it is perfectly possible to use it as is.
source to share