AngularJS/AngularJS

▶ Angular2 기본개념 : EventEmitter를 활용한 버튼토글이벤트(Button Toggle Event) 예제

비주얼라이즈 2016. 9. 10. 22:39

EventEmitter의 기본개념 및 간단예제


이번 글에서는 Angular2의 기본 개념중, 'EventEmitter'에 대해서 간단히 정리해보고자한다.





EventEmitter의 기본개념


EventEmitter 는 Angular2에서 directives와 custom event를 emit하는 component에서 사용된다.


여기서 emit이라는 단어의 사전적정의를 살펴보면 '발산, 방출하다.'이다. 

이를 '호출하다'라고 이해하면 혼란스럽기 때문에, 이벤트 호출과는 다른 개념이라는 것을 먼저 알아두면 좋다.



Class OverView

 EventEmitter의 기본적인 구성은 다음과 같다. 

class EventEmitter {
    constructor(isAsync?: boolean)
    emit(value?: T)
    subscribe(generatorOrNext?: any, error?: any, complete?: any) : any
}




▶ Angular2 기본개념 : EventEmitter를 활용한 버튼토글이벤트(Button Toggle Event) 예제


다음 코드에서  'Toggle'이라는 메시지가 담긴 영역을 클릭하면, "zippy" 클래스는 open과 close라는 두 가지 이벤트를 각 상황에 맞게 방출(emit)한다.



@Component({
  selector: 'zippy',
  template: `
  <div class="zippy">
     <div (click)="toggle()">Toggle </div>
     <div [hidden]="!visible">
       <ng-content> >/ng-content>
     </div>
   </div>`
})

export class Zippy {
  visible: boolean = true;
  @Output() open: EventEmitter = new EventEmitter();
  @Output() close: EventEmitter = new EventEmitter();
  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      this.open.emit(null);
    } else {
      this.close.emit(null);
    }
  }