reassign .this to a fixed object for methods
npm install @badhands/bindallob - Object to bind methods to.
fns - is an object whose values get fixed bound to ob
selected - Array of string providing names of selected functions to bind - in case when binding needs to be done selectively.
npm install @badhands/bindAll
`
#### Internals
- reassign `.this` to fixed object for selected functions
- mutates fns that holds the functions
- Other implementation ( lodash, underscore ) of bindAll does not provide option to control what fns is bound to.
- 40 lines of code.
#### Examples
. . binding all functions in object
| livescript |
| --- |
`javascript
bindAll = require("@badhands/bindAll")
ob =
{
fuel:"coffee",
fns:
{
foo:function(){
console.log(this)
}
}
}
ob.fns.foo() // { foo: [Function: foo] } // cannot access .fuel :(
bindAll(ob,ob.fns) // will mutate original object
ob.fns.foo() // { fuel: 'coffee', fns: { foo: [Function] } }
// can access .fuel now !
`
. . for applying to a subset number of functions
| livescript |
| --- |
`javascript
ob =
{
fuel:"coffee",
fns:
foo:function()
{
console.log(this)
}
bar:function()
{
console.log(this)
}
}
bindAll(ob , ob.fns , ["bar"])
ob.fns.bar()
// { fuel: 'coffee', fns: { log: [Function] , bar: [Function] } }
ob.fns.foo()
// { fns: { log: [Function] , bar: [Function] } }
``