Ad

Removing Debounced Callback

- 1 answer

I have the following code inside of a React store:

  addChangeListener(cb) {
    this.on(CHANGE_EVENT, _.debounce(cb, 100));
  }

  removeChangeListener(cb) {
    _.debounce(cb).cancel();
    this.removeListener(CHANGE_EVENT, cb);
  }

I don't believe that removeChangeListener is removing the cb because of the _.debounce function. How can I use _.debounce, and also ensure that the proper cb is removed?

Ad

Answer

You are correct. _.debounce creates a new function. So you need to do something like:

var debouncedCb;

addChangeListener(cb) {
  debouncedCb = _.debounce(cb, 100)
  this.on(CHANGE_EVENT, debouncedCb);
}

removeChangeListener(cb) {
  this.removeListener(CHANGE_EVENT, debouncedCb);
  _.debounce(cb).cancel();
}

Depending on you're specifics, you'll probably want to attach debouncedCb to cb somehow, so that removeChangeListener doesn't get confused.

Ad
source: stackoverflow.com
Ad