Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of binds on an event

Tags:

I have got a child component which shows a table of data. I want to provide a "select" button on every row, but only if the table is shown in a context where the button is needed, i.e. the table might be shown either standalone or as a selection for a form field.

My idea is to use an EventEmitter for the "select" button and display the button only if there are any subscribers to the event. How is this achieved or are there any better ways to do this?

I'm using angular 2 rc.5

Edit: Example code:

@Component({directives: [Child], template: "<child (select)="onSelect()"></child>"})
class Parent {
}

@Component({selector: "child", template: "<div *ngIf="showSelect" (click)="onSelect()">select</div>"})
class Child {
    @Output("select") select: EventEmitter<any> = new EventEmitter<any>();
    get showSelect() {
        // return true if there is any subscription to Output("select") 
    }
}

The DIV in the Child component should only be shown if the parent defines a listener to this "select" event. In this case it does by binding it in the template, but it should also work if someone calls .subscribe() directly on the Child component's "select" property.

like image 292
Normalo Avatar asked Aug 25 '16 05:08

Normalo


1 Answers

select.observers.length will tell you how many subscribers there are on an EventEmitter (in this example, for an EventEmitter named 'select'). The general pattern is <myEmitter>.observers.length.

0 means you have a subscriber.

like image 164
TimTheEnchanter Avatar answered Sep 25 '22 16:09

TimTheEnchanter