Getting the event object with Underscore debounce[

2019-07-16 09:30发布

问题:

I am trying to use debounce on an action I have managed to do that however I want to pass e through as a parameter but it is not working. Is there any way I could do this?

 constructor(props, context) {
    super(props, context);
    this.testing = _.debounce(this.testing.bind(this), 2000);
}

 @action testing(e) {
     alert("debounced!!");
     //use e.target ... 
   }

If I take away e it will get into the function otherwise not. What should I do to resolve this?

回答1:

You can make use of event.persist() to pass on the event to the debounce method.

According to the DOCS:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

So you can use the event as

constructor(props, context) {
    super(props, context);
    this.testing = _.debounce(this.testing.bind(this), 2000);
}

 @action testing(e) {
     alert("debounced!!");
     //use e.target ... 
   }
onChange = (e) => {
    e.persist();
    this.testing(e);
}


回答2:

After assigning this.testing,

this.testing = _.debounce(this.testing.bind(this), 2000);

in some event you should call that method with parameter

onSumbit(e){
    this.testing(e);
}

something like this