2016-02-28 193 views
2

我想知道在移動或在某個對象上單擊鼠標時如何觸發指令功能。Angular2指令,鼠標移動事件

我發現這部分代碼,我認爲會做我想做的。我不確定語法和實際發生的事情。

由於指令類的一部分,我有這樣的:

mousedown = new EventEmitter(); 
@HostListener('mousedown', ['$event']) 
onMousedown(event) { 
    console.log(event); 
    this.mousedown.emit(event); 
} 

其中,如果我點擊具有指令的股利,正在打印事件到控制檯預期。雖然我不確定第二行如何使用this.mousedown.emit()

實際上用.emit()函數調用了什麼?

回答

1

mousedown = new EventEmitter();對於您的用例似乎是多餘的。如果您添加了一個@Output()註釋,那麼您會收聽mousedown事件,並立即發出另一個註釋。

更新

@Directive({ 
    selector: '[clickToOtherEvent]' 
}) 
class EventTranslator { 
    @Output() otherEvent = new EventEmitter(); 

    @HostListener('mousedown', ['$event']) 
    onMousedown(event) { 
    console.log(event); 
    this.otherEvent.emit(event); 
    } 
} 

您可以使用該指令像

<button clickToOtherEvent (otherEvent)="doSomething()">test output</button> 

的指令聽mousedown事件,併發出otherEvent可以再次聆聽。

+0

我不知道如何,你可以提交一個輸出裝飾器的例子嗎? – theva

+0

所以我不能真正把它放到我的腦海裏,是另一個事件,我必須實現一個函數,在調用.emit時調用它? – theva

+0

我只是試圖詳細說明你的問題中包含的'EventEmitter'行。當你只是想聽「mousedown」事件並採取行動時,你根本不需要這條線。 '@Output()...'行是一個自定義事件。使用您的指令的組件可以偵聽該事件。我的答案中的代碼是聽取'mousedown'事件,並在'onMouseDown'中爲每個傳入的'mousedown'事件觸發'otherEvent'。 HTML示例行監聽此事件可以在從'clickToOtherEvent'指令觸發時調用'doSomething()'。 –