From fac2fc56004bd1509620f39bb24896996edc0030 Mon Sep 17 00:00:00 2001 From: Bryce Johnson Date: Fri, 19 May 2017 14:11:57 +0000 Subject: Document a convention for binding event handlers. --- doc/development/fe_guide/style_guide_js.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/doc/development/fe_guide/style_guide_js.md b/doc/development/fe_guide/style_guide_js.md index d2d89517241..1879025ebb7 100644 --- a/doc/development/fe_guide/style_guide_js.md +++ b/doc/development/fe_guide/style_guide_js.md @@ -221,6 +221,33 @@ A forEach will cause side effects, it will be mutating the array being iterated. Add User ``` + +#### Event handling + +1. When registering an event listener, prefer to implicitly bind the context of +the handler with an arrow function, rather than explicitly with `.bind(this)`. + + ```javascript + // bad + $('.my-button').on('click', this.myMethod.bind(this)); + + + // good + $('.my-button').on('click', e => this.myMethod(e)); + + ``` + +2. In the rare cases where the context you need to bind isn't in lexical +scope, or it makes sense to set parameters at the time of binding, it's okay to +use `.bind()`. + + ```javascript + // okay + $('.my-button').on('click', e => this.myMethod.bind(superClass)); + + // okay + $('.my-button').on('click', e => this.myMethod.bind(superClass, myParam, yourParam)); + ``` ### Vue.js -- cgit v1.2.1