简体   繁体   中英

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()" />

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM