Underscore: _.debounce() loses event.currentTarget

Created on 23 Oct 2014  ·  8Comments  ·  Source: jashkenas/underscore

I am unable to get the event.currentTarget when using addEventListener with _.debounce().

Here’s a fiddle.

Most helpful comment

@jridgewell any idea how to get around this in a React onChange. when i don't use debounce I am able to access the proper event in my onChange function but when I use _.debounce I lose the proper event – see below

// in my render
<input onChange={ _.debounce(this.updateNote.bind(this), 500) } />
// my change handler
updateNote(event) {
    // undefined on event.target, get lodash event not <input/> event target
    const note = event.target.value
    this.sendNote({ note })
 }

All 8 comments

If the property is changed on the event object reference that's outside the scope of Underscore. If you use a lib like jQuery that may help as they make a synthetic event object which you should be able to reference without issue.

I don't think you're going to get around this. event is reused as it propagates up the DOM, with currentTarget changing for each element with a listener. fiddle

Passing a second parameter can get around this. fiddle

var debounced = _.debounce(fn, 50);
document.querySelector('.debounced-input').addEventListener('keyup', function(event) {
    debounced(event, event.currentTarget);
});

Yep, this is outside of the scope of underscore. Consider a DOM event micro framework like gator

Here's an example of it working with jQuery.

I can still get the element that currentTarget usually has with this; I just opened this issue to make sure what I’m seeing is actually expected behaviour.

@jridgewell any idea how to get around this in a React onChange. when i don't use debounce I am able to access the proper event in my onChange function but when I use _.debounce I lose the proper event – see below

// in my render
<input onChange={ _.debounce(this.updateNote.bind(this), 500) } />
// my change handler
updateNote(event) {
    // undefined on event.target, get lodash event not <input/> event target
    const note = event.target.value
    this.sendNote({ note })
 }

This is a matter of implementation. You need to persist the event. onChange should call a persist and THEN pass the persisted event to the debounced handler:

onChange_persist = (e) =>
{
    e.persist();
    e.onChange_debounced(e);
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

sky0014 picture sky0014  ·  8Comments

danilopolani picture danilopolani  ·  5Comments

xiaoliwang picture xiaoliwang  ·  3Comments

chikamichi picture chikamichi  ·  8Comments

ksullivan picture ksullivan  ·  9Comments