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

我的梦境 提交于 2021-02-08 05:10:20

问题


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

回答1:


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>



回答2:


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.....



来源:https://stackoverflow.com/questions/55865887/how-to-trigger-only-one-event-change-or-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!