请选择 进入手机版 | 继续访问电脑版

技术控

    今日:47| 主题:53603
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Do you even need that bind?

[复制链接]
分手后S朋友 发表于 2016-11-30 19:56:53
131 1

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Codereviewer: “Why is this binding necessary?”
  1. <Modal show={viewStore.modal.show}
  2.        closeOnOuterClick={true}
  3.        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.”
  

Do you even need that bind?

Do you even need that bind?
   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. ��
  Let’s investigate.

  Here’s a self-contained example in Codepen – a clicker.
   See the Pen React, mobx, bind example by Swizec Teller ( @swizec ) on CodePen .light
   We have a Store that holds the number of clicks and contains an inc action to increase the count.
   
  1. class Store {
  2.   @observable clicks = 0;
  3.   @action inc() {
  4.     this.clicks += 1;
  5.   }
  6. }
复制代码
    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.
   
  1. const Clicky = observer(({ store }) => (
  2.   <div>
  3.     Clicks: {store.clicks}
  4.     <br />
  5.     <a href="#" onClick={store.inc.bind(store)}>+1</a>
  6.   </div>
  7. ));
复制代码
   

Do you even need that bind?

Do you even need that bind?
  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 .light
   We expanded our Clicky component with a link that uses an unbounded store.inc action call as the onClick callback.
   
  1. const Clicky = observer(({ store }) => (
  2.   <div>
  3.     Clicks: {store.clicks}
  4.     <br />
  5.     <a href="#" onClick={store.inc.bind(store)}>+1 bound</a>
  6.     <br />
  7.     <a href="#" onClick={store.inc}>+1 unbound</a>
  8.   </div>
  9. ));
复制代码
   

Do you even need that bind?

Do you even need that bind?
  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.
  A spelunk through a React event

  

Do you even need that bind?

Do you even need that bind?
   It starts with dispatchEvent .
   
  1. dispatchEvent: function (topLevelType, nativeEvent) {
  2.     if (!ReactEventListener._enabled) {
  3.       return;
  4.     }
  5.     var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
  6.     try {
  7.       // Event queue being processed in the same cycle allows
  8.       // `preventDefault`.
  9.       ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
  10.     } finally {
  11.       TopLevelCallbackBookKeeping.release(bookKeeping);
  12.     }
  13.   }
复制代码
   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 .
   
  1. var transaction = new ReactDefaultBatchingStrategyTransaction();
  2. var ReactDefaultBatchingStrategy = {
  3.   isBatchingUpdates: false,
  4.   /**
  5.    * Call the provided function in a context within which calls to `setState`
  6.    * and friends are batched such that components aren't updated unnecessarily.
  7.    */
  8.   batchedUpdates: function (callback, a, b, c, d, e) {
  9.     var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
  10.     ReactDefaultBatchingStrategy.isBatchingUpdates = true;
  11.     // The code is written this way to avoid extra allocations
  12.     if (alreadyBatchingUpdates) {
  13.       callback(a, b, c, d, e);
  14.     } else {
  15.       transaction.perform(callback, null, a, b, c, d, e);
  16.     }
  17.   }
  18. };
复制代码
    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 .
   
  1. perform: function (method, scope, a, b, c, d, e, f) {
  2.     !!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0;
  3.     var errorThrown;
  4.     var ret;
  5.     try {
  6.       this._isInTransaction = true;
  7.       // Catching errors makes debugging more difficult, so we start with
  8.       // errorThrown set to true before setting it to false after calling
  9.       // close -- if it's still set to true in the finally block, it means
  10.       // one of these calls threw.
  11.       errorThrown = true;
  12.       this.initializeAll(0);
  13.       ret = method.call(scope, a, b, c, d, e, f);
  14.       errorThrown = false;
  15.     } finally {
  16.       try {
  17.         if (errorThrown) {
  18.           // If `method` throws, prefer to show that stack trace over any thrown
  19.           // by invoking `closeAll`.
  20.           try {
  21.             this.closeAll(0);
  22.           } catch (err) {}
  23.         } else {
  24.           // Since `method` didn't throw, we don't want to silence the exception
  25.           // here.
  26.           this.closeAll(0);
  27.         }
  28.       } finally {
  29.         this._isInTransaction = false;
  30.       }
  31.     }
  32.     return ret;
  33.   },
复制代码
   :flushed:
  That’s a lot of code. Let’s focus on the bits that matter:
   
  1. perform: function (method, scope, a, b, c, d, e, f) {
  2. // ...
  3.       ret = method.call(scope, a, b, c, d, e, f);
  4. // ...
复制代码
    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 .
  ¯_(ツ)_/¯
  What did we learn

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



上一篇:This Week in Spring: Reactive Programming and Springing to the Cloud
下一篇:Quick TR069 Botnet Writeup + Triage
zhangyuedong 发表于 2016-12-9 04:44:08
梦想不能实现,都是因为它不够现实。
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表