1

Can someone help explain what is the use of bind in this context is?

<button onClick={this.add.bind(null, 'Bacon tuna')} className="button-info-create">Add New</button>

https://youtu.be/OKRu7i49X54?list=PL6gx4Cwl9DGBuKtLgPR_zWYnrwv-JllpA&t=3m3s

From what I understand, when null passed to bind, this refers to the global scope. Yet somehow it is seems to be referring to the Board instance.

2 Answers 2

3

bind allows you to seed arguments into the resulting function.

fun.bind(thisArg[, arg1[, arg2[, ...]]])

so that is calling this.add, passing in null for the context (which is ignored when the constructor is called with new), and seeding "bacon tuna" for the first argument.

you can read more about function.prototype.bind here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Sign up to request clarification or add additional context in comments.

Comments

1

React.createClass() will automatically bind this values correctly for us, but changes when using ES6 classes affect this, source

This is the reason why on the video, bind(null, 'something') could be used even if add() method is using this.setState(). If you try to use bind(null, ...) with extends React.Component instead of React.createClass, it will not work.

If you open the source link, you can read very detailed and longer explanation by Todd Motto.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.