What is the proper use of an EventEmitter?

后端 未结 4 1750
无人及你
无人及你 2020-11-22 01:53

I\'ve read questions like Access EventEmitter Service inside of CustomHttp where the user uses EventEmitter in his service, but he was suggested in this comment not to use

4条回答
  •  难免孤独
    2020-11-22 02:16

    TL;DR:

    No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.

    Answer:

    No, you should not subscribe manually to it.

    EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald

    [...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

    This is stated really clear in EventEmitter's documentation.

    Use by directives and components to emit custom Events.

    What's wrong about using it?

    Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit() method. We should never subscribe manually to an EventEmitter.

    All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference

    Do NOT count on EventEmitter continuing to be an Observable!

    Do NOT count on those Observable operators being there in the future!

    These will be deprecated soon and probably removed before release.

    Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

    His comment is in line with Rob's comment long time ago.

    So, how to use it properly?

    Simply use it to emit events from your component. Take a look a the following example.

    @Component({
        selector : 'child',
        template : `
            
        `
    })
    class Child {
        @Output() notifyParent: EventEmitter = new EventEmitter();
        sendNotification() {
            this.notifyParent.emit('Some value to send to the parent');
        }
    }
    
    @Component({
        selector : 'parent',
        template : `
            
        `
    })
    class Parent {
        getNotification(evt) {
            // Do something with the notification (evt) sent by the child!
        }
    }
    

    How not to use it?

    class MyService {
        @Output() myServiceEvent : EventEmitter = new EventEmitter();
    }
    

    Stop right there... you're already wrong...

    Hopefully these two simple examples will clarify EventEmitter's proper usage.

提交回复
热议问题