All files / src/utils autobind.js

100% Statements 4/4
100% Branches 0/0
100% Functions 1/1
100% Lines 4/4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28                                          48x 48x 224x 224x      
/**
* Copyright 2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
 
import assert from '../assert';
 
/**
 * Automatically bind all given methods to the class instance.
 *
 * @param {object} object - instance to bind the method to
 * @param {string} arguments - methods of the instance to bind
 *
 * Note that class properties with arrows aren't a good solution
 * to the binding problem.
 * See e.g. https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1
 */
export default function autoBind(instance) {
  assert(arguments.length > 1, "Must provide methods for binding");
  for (let i = 1; i < arguments.length; i++) {
    const k = arguments[i];
    instance[k] = instance[k].bind(instance);
  }
}