Bala
Bala

Reputation: 11234

Understanding this.method.bind(null,...) in ReactJS?

I am working through examples learning ReactJS (Mastering React). While recreating examples, I am clueless with couple of statements and would appreciate some help.

Fiddle: Composing Components

First

...
//Why are we passing null in update.bind(...)?
//Is null here equivalent to 'this'?

<TextBox label='First Name' update={this.update.bind(null,'firstName')}></TextBox>
...

Second

Update method expects a key and a value (method definition below)

...
    update: function(key, value) {
            var newState = {};
            newState[key] = value;
            this.setState(newState);

            //this.setState({[k]:v});
        },
...

However, when it is called with a single parameter, correct key is updated with the right value.

//Aren't we supposed to pass two parameters?  
this.props.update(this.refs.newText.value);

Upvotes: 4

Views: 2264

Answers (2)

David McIntyre
David McIntyre

Reputation: 74

'Bind' is an example of how to implement the "currying" pattern in javascript. In this case it wraps the update method so that whenever update is called, this is null and 'firstName' will be the first argument (key in this case).

Unless i'm missing something, the value of 'this' when the update method is invoked will be null, unless you replace null in the bind() with bind(this, 'firstName')

Upvotes: 2

Oleksandr T.
Oleksandr T.

Reputation: 77482

this.update.bind(null,'firstName') that code means - set for this.update this to null, and set first argument as a 'firstName', then when you will call this reference to function - first argument will be 'firstName' and second you can set by yourself., we can simplify code from your example like this

var fn = function (key, value) {
  console.log(key);
  console.log(value);
};

var f = fn.bind(null, 'x');

f('y');

Upvotes: 6

Related Questions