Add bindAll

This commit is contained in:
Angelos Chalaris
2018-01-26 14:14:53 +02:00
parent eae232829c
commit 089b81ff2e
2 changed files with 28 additions and 1 deletions

26
snippets/bindAll.md Normal file
View File

@ -0,0 +1,26 @@
### bindAll
Explain briefly what the snippet does.
Use `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified.
```js
const bindAll = (obj, ...fns) =>
fns.forEach(
fn =>
(obj[fn] = function() {
return fn.apply(obj);
})
);
```
```js
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.
```