Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - Programmatically (un)register to event with Angular 2

I have a directive that listens to some events using the host property of the @directive decorator. This works great, but I don't need all events at all times.

For example, I'm only interested in (document: mouseup) at certain times (namely after a mousedown on my element).

What is the angular way to register and unregister to events dynamically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you register imperatively you can unregister the same way. AFAIK for declaratively added listeners there is no way to unregister.

import {DOM} from 'angular2/platform/common_dom.dart';

DOM
    .getGlobalEventTarget('window')
    .addEventListener('message', function, false);
    //.remove...

See also https://github.com/angular/angular/issues/6904

You could also just use

document.addEventListener
        // remove ...

but direct DOM access is discouraged. But in the comments of the linked issue they seem to see the first approach as direct DOM access as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...