Anoop chaudhary
Anoop chaudhary

Reputation: 87

How to trigger only one event 'change' or 'click'

I have a number input tag on which I have two event listeners 'on-click' and 'on-change'. When I am click on arrow it triggers both. I would like to have one whichever triggers first without removing any of the event listeners. On clicking rapidly change event doesn't trigger until it looses focus from input tag(If I keep only change event). If I keep only click event then I won't be able to capture change event.

<input type="number" @click="function()" @change="function()" />

Upvotes: 2

Views: 1496

Answers (2)

zeev gerstner
zeev gerstner

Reputation: 15

You can add to data a boolian (e.g isInvoked:false). When the function run check:

if (this.isInvoked) return; this.isInvoked=true; //rest of your code here.....

Upvotes: 0

Michael Oosthuizen
Michael Oosthuizen

Reputation: 144

Use Observables. You can think about them as streams for events. Debouncing the output should give the result you want.

var event_a = Rx.Observable.fromEvent(document, 'mousemove'); 
var event_b = Rx.Observable.fromEvent(document, 'click'); // or in this case (input_element, 'click')

var debounce_ms = 100;
var debounced_event = merge(event_a, event_b).debounceTime(debounce_ms);

The debouncing step removes multiple events that happen in the specified time interval. If both events (or more than one copy of the same event) happens in less than 100 ms, only one event will be emitted.

On debouncing Observables: https://www.learnrxjs.io/operators/filtering/debouncetime.html

The above example uses different events from yours; just adapt it to listen to any of the events that you want. Lastly, subscribe to the Observable, and call the relevant event handling code there:

debounced_event.subscribe(() => {
    // do event handling things here
});

To use Observables on your page, include rx.js somewhere. Here is example code to load it from a CDN.

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.1/rxjs.umd.js"></script>

Upvotes: 1

Related Questions