Codereviewer: "Why is this binding necessary?"

<Modal show={viewStore.modal.show} closeOnOuterClick={true} onClose={viewStore.closeModal.bind(viewStore)}

This code follows my Simple MobX-driven modals approach.

Swiz: "Without binding, the callback would bind to Modal object when called, if I'm not mistaken."

Codereviewer: "Would it? That doesn't seem very intuitive."

Swiz: "Welcome to JavaScript's dynamic scoping. Where have you been the past few years?…

But you're right, it does seem to work. I think MobX's @action does a bind for us. It definitely wouldn't work with vanilla functions. I'll change the code code."

Nope, no, nah. I should not have done that. That did not work. @action does not do any binding. Wrapping a function in a function does not create a closure with the correct local scope.

But it did work in that one case I tried. Just not in the other. ?

Here's a self-contained example in Codepen - a clicker.

See the Pen React, mobx, bind example by Swizec Teller (@swizec) on CodePen.

We have a Store that holds the number of clicks and contains an inc action to increase the count.

class Store { @observable clicks = 0 ; @action inc ( ) { this . clicks += 1 ; } }

A not-very-smart functional stateless component renders the current count and a link to click. We use onClick with a bounded action to detect clicks.

const Clicky = observer ( ( { store } ) => ( < div > Clicks : { store . clicks } < br > < a href = "#" onclick = { store . inc . bind ( store ) } > + 1 < / a > < / div > ) ) ;

Click the link, number goes up. 14 lines of actual code.

Ok, we know it works with a .bind . Will it work without one?

See the Pen React, mobx, bind example, pt2 by Swizec Teller (@swizec) on CodePen.

We expanded our Clicky component with a link that uses an unbounded store.inc action call as the onClick callback.

const Clicky = observer ( ( { store } ) => ( < div > Clicks : { store . clicks } < br > < a href = "#" onclick = { store . inc . bind ( store ) } > + 1 bound < / a > < br > < a href = "#" onclick = { store . inc } > + 1 unbound < / a > < / div > ) ) ;

Well, that didn't work. ?

The error reads Uncaught TypeError: Cannot read property 'clicks' of undefined . Looks like this isn't defined inside our callback.

Good ol' dynamic scoping, unintuitive as always. If that Wikipedia article doesn't tell you much, don't worry. It's basically comp sci soup.

The gist of their 800-word explanation is this: with dynamic scoping, functions are scoped to where they're called, not where they're defined. It doesn't matter that inc is defined inside Store ; it matters how React calls it.

So how does React call our click callback? Let's see.

It starts with dispatchEvent .

dispatchEvent : function ( topLevelType , nativeEvent ) { if ( ! ReactEventListener . _enabled ) { return ; } var bookKeeping = TopLevelCallbackBookKeeping . getPooled ( topLevelType , nativeEvent ) ; try { ReactUpdates . batchedUpdates ( handleTopLevelImpl , bookKeeping ) ; } finally { TopLevelCallbackBookKeeping . release ( bookKeeping ) ; } }

Looks like a function that takes native events from the browser and emits them into React's engine in batches. That's good for performance, great for debugging, and makes everyone's lives easier.

Our next step in the chain is batchedUpdates .

var transaction = new ReactDefaultBatchingStrategyTransaction ( ) ; var ReactDefaultBatchingStrategy = { isBatchingUpdates : false , batchedUpdates : function ( callback , a , b , c , d , e ) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy . isBatchingUpdates ; ReactDefaultBatchingStrategy . isBatchingUpdates = true ; if ( alreadyBatchingUpdates ) { callback ( a , b , c , d , e ) ; } else { transaction . perform ( callback , null , a , b , c , d , e ) ; } } , } ;

Told ya it was good for performance. Just look at that comment – "components aren't updated unnecessarily".

I have no idea how this thing works. It smells like some sort of currying.

But we know our next step, eventually, is transaction.perform .

perform : function ( method , scope , a , b , c , d , e , f ) { ! ! this . isInTransaction ( ) ? "development" !== 'production' ? invariant ( false , 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.' ) : _prodInvariant ( '27' ) : void 0 ; var errorThrown ; var ret ; try { this . _isInTransaction = true ; errorThrown = true ; this . initializeAll ( 0 ) ; ret = method . call ( scope , a , b , c , d , e , f ) ; errorThrown = false ; } finally { try { if ( errorThrown ) { try { this . closeAll ( 0 ) ; } catch ( err ) { } } else { this . closeAll ( 0 ) ; } } finally { this . _isInTransaction = false ; } } return ret ; } ,

?

That's a lot of code. Let's focus on the bits that matter:

perform : function ( method , scope , a , b , c , d , e , f ) { ret = method . call ( scope , a , b , c , d , e , f ) ;

A-ha! The second argument is scope . React specifically set that to null when calling transaction.perform , and function.call is a JavaScript way to define a function's scope at point of invocation.

The call() method calls a function with a given this value and arguments provided individually.

I don't know why React goes out of its way to set callback scope to null , but I'm sure it has something to do with correctness. Better to throw an explicit error and tell the engineer to fix their code than to get the wrong this by accident and fuck shit up.

And I'm not sure when, if ever, that scope argument would be something other than null .

¯ _ (ツ) _ /¯

Bind your callbacks.

Add a .bind or a fat arrow wrap -> () => callback() . Both work.

Did you enjoy this article? 👎 👍

Published on November 29th, 2016 in Technical

Learned something new?

Want to become a high value JavaScript expert? Here's how it works 👇 Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths. Start with an interactive cheatsheet 📖 Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. "Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌" ~ Ashish Kumar Your Name Your Email Your Address Subscribe & Become an expert 💌 Join over 10,000 engineers just like you already improving their JS careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️