Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event delegation in Angular2

I'm developing an app in ng2 and I'm struggling with something. I'm building a calendar where you can pick a date-range and I need to react on click & mouseenter/mouseleave events on day cells. So I have a code (simplified) like this:

calendar.component.html

<month>
    <day *ngFor="let day of days" (click)="handleClick()" 
         (mouseenter)="handleMouseEnter()" 
         (mouseleave)="handleMouseLeave()" 
         [innerHTML]="day"></day>
</month>

But this gives me hundreds of separate event listeners in the browser's memory (each day's cell gets 3 event listeners, and I can have up to 12 months displayed at a time so it would be over 1k of listeners).

So I wanted to do it "the proper way", using the method called "event delegation". I mean, attach a click event on the parent component (month) and when it receives a click event, simply check whether it occurred on Day component - and only then I would react to this click. Something like jQuery does in it's on() method when you pass it the selector parameter.

But I was doing it by referencing the DOM elements natively in the handler's code:

month.component.ts

private handleClick(event) {
    if (event.target.tagName === 'DAY') {
        // handle day click
    } else {
        // handle other cases
    }
}

and my colleagues rejected my idea, since - as they said - "There must be a simpler, proper way of handling this in NG2; like there is in jQuery. Besides, it's getting out of control here - you're reacting to Day's clicks in Month's code."

So, my question is, is there a better way? Or am I trying to solve a problem which I shouldn't bother solving anymore, since users' devices get more and more memory/processing power everyday?

Thanks in advance!

like image 274
Michal Leszczyk Avatar asked Jul 06 '16 11:07

Michal Leszczyk


People also ask

What is delegation in Angular?

With delegation, one object will contain a reference to a different object that it will hand off a request to perform the functionality. The code below shows how to use delegation with the Bird class and Penguin class.

What is event delegation and event bubbling?

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.

How does Angular handle click event?

Events are handled in Angular using the following special syntax. Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.

What is event target in Angular?

The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target. value . In the following example the code sets the <input> value property by binding to the name property.


1 Answers

Intro

I stumbled across this today, and I can really see the need for this implementation in a lot of applications. Now I can't vouch that this is 100% the best technique however I have gone out of my way to make this approach as angular inspired as possible.

The approach that I have come up with has 2 stages. Both stage 1 and stage 2 will add a total of years * months + years * months * days, so for 1 year you will have 12 + 365 events.


Stage Scope

Stage 1: Delegate events from when a month is clicked down into the actual day which was clicked without requiring an event on the day.
Stage 2: Propagate the chosen day back to the month.

Just before delving in, the application consists of 3 components which are nested in the following order: app => month => day


This is all the html that is required. app.component hosts a number of months, month.component hosts a number of days and day.component does nothing but display it's day as text.

app.component.html

<app-month *ngFor="let month of months" [data-month]="month"></app-month>

month.component.html

<app-day *ngFor="let day of days" [data-day]="day">{{day}}</app-day>

day.component.html

<ng-content></ng-content>

This is pretty stock standard stuff.


Stage 1

Let's have a look at the month.component.ts where we want to delegate our event from.

// obtain a reference to the month(this) element 
constructor(private element: ElementRef) { }

// when this component is clicked...
@HostListener('click', ['$event'])
public onMonthClick(event) {
  // check to see whether the target element was a child or if it was in-fact this element
  if (event.target != this.element.nativeElement) {
    // if it was a child, then delegate our event to it.
    // this is a little bit of javascript trickery where we are going to dispatch a custom event named 'delegateclick' on the target.
    event.target.dispatchEvent(new CustomEvent('delegateEvent'));
  }
}

In both stage 1 and 2, there is only 1 caveat and that is; if you have nested child elements within your day.component.html, you will need to either implement bubbling for this, better logic in that if statement, or a quick hack would be.. in day.component.css :host *{pointer-events: none;}


Now we need to tell our day.component to be expecting our delegateEvent event. So in day.component.ts all you have to do (in the most angular way possible) is...
@HostListener('delegateEvent', ['$event'])
 public onEvent() {
   console.log("i've been clicked via a delegate!");
 }

This works because typescript doesn't care about whether the event is native or not, it will just bind a new javascript event to the element and thus allows us to call it "natively" via event.target.dispatchEvent as we do above in month.component.ts.

That concludes Stage 1, we are now successfully delegating events from our month to our days.


Stage 2

So what happens if we say want to run a little bit of logic in our delegated event within day.component and then return it to month.component - so that it can then carry on with its own functionality in a very object oriented method? Well fortunately, we can very easily implement this!

In month.component.ts update to the following. All that has changed is that we are now going to pass a function with our event invocation and we defined our callback function.

@HostListener('click', ['$event'])
  public onMonthClick(event) {  
    if (event.target != this.element.nativeElement) {
      event.target.dispatchEvent(new CustomEvent('delegateEvent', { detail: this.eventDelegateCallback}));
    }
  }

  public eventDelegateCallback(data) {
    console.log(data);
  }

All that is left is to invoke this function within day.component.ts...

public onEvent(event) {
    // run whatever logic you like, 
    //return whatever data you like to month.component
    event.detail(this.day);
}

Unfortunately our callback function is a little ambiguously named here, however typescript will complain about the property not being a defined object literal for CustomEventInit if named otherwise.


Multiple Event Funnel

The other cool thing about this approach is that you should never have to define more than this number of events because you can just funnel all events through this delegation and then run logic within day.component.ts to filter by event.type...

month.component.ts

@HostListener('click', ['$event'])
@HostListener('mouseover', ['$event'])
@HostListener('mouseout', ['$event'])
  public onMonthEvent(event) {  
    if (event.target != this.element.nativeElement) {
      event.target.dispatchEvent(new CustomEvent('delegateEvent', { detail: this.eventDelegateCallback }));
    }
  }

day.component.ts

private eventDelegateCallback: any;

@HostListener('delegateEvent', ['$event'])
  public onEvent(event) {
    this.eventDelegateCallback = event.detail;
    if(event.type == "click"){
       // run click stuff
       this.eventDelegateCallback(this.day)
    }
  }
like image 69
Zze Avatar answered Oct 14 '22 00:10

Zze