0

I have implemented react component on change event like this:

NewItem = React.createClass({

  componentWillMount: function() {
    this._searchBoxHandler = debounce(this._searchBoxHandler, 500);
  },

  _searchBoxHandler: function(event) {
    this.context.flux.getActions('order').setOrders(...);
  },

  render: function () {
    ...
    var _self = this;
    return (<TextField onChange={_self._searchBoxHandler} />)      
  })

});

I've done this implemention by checking this answer (Good idea section): https://stackoverflow.com/a/28046731/842622

But it's not working. I'm always having 'Cannot read property 'value' of null' from event object.

Am I missing something here?

Community
  • 1
  • 1
Mirat Can Bayrak
  • 631
  • 7
  • 18

1 Answers1

0

You need to bind your context or use a closure to maintain scoping:

NewItem = React.createClass({

  componentWillMount: function() {
    this._searchBoxHandler = debounce(this._searchBoxHandler.bind(this), 500);
  },

  _searchBoxHandler: function(event) {
    this.context.flux.getActions('order').setOrders(...);
  },

  render: function () {
    ...
    var _self = this;
    return (<TextField onChange={_self._searchBoxHandler} />)      
  })

});

A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g. by using that method in callback-based code). Without special care however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem.. - MDN

Some nice docs on binding and context: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

or you could use a 'fat-arrow' function to access parent class scope:

debounce((event) => { this._searchBoxHandler(event); }, 500);

Note: I wouldn't overwrite the declared function property in the componentWillMount invocation, instead you could store the debounced instance in another property like _debouncedSearchBoxHandler

Cristian Cavalli
  • 2,619
  • 1
  • 13
  • 11