Files
30-seconds-of-code/snippets/bindAll.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

692 B

title, tags
title tags
bindAll object,function,intermediate

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.prototype.forEach() to return a function that uses Function.prototype.apply() to apply the given context (obj) to fn for each function specified.

const bindAll = (obj, ...fns) =>
  fns.forEach(
    fn => (
      (f = obj[fn]),
      (obj[fn] = function() {
        return f.apply(obj);
      })
    )
  );
var view = {
  label: 'docs',
  click: function() {
    console.log('clicked ' + this.label);
  }
};
bindAll(view, 'click');
jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked.