@@ -33,15 +33,15 @@ export interface Obj extends Object {
33
33
}
34
34
35
35
/**
36
- * Binds and copies functions onto an object
36
+ * Builds proxy functions on the `to` object which pass through to the `from` object.
37
37
*
38
- * Takes functions from the 'from' object, binds those functions to the _this object, and puts the bound functions
39
- * on the 'to' object.
38
+ * For each key in `fnNames`, creates a proxy function on the `to` object.
39
+ * The proxy function calls the real function on the `from` object.
40
40
*
41
- * This example creates an new class instance whose functions are prebound to the new'd object.
42
- * @example
43
- * ```
44
41
*
42
+ * #### Example:
43
+ * This example creates an new class instance whose functions are prebound to the new'd object.
44
+ * ```js
45
45
* class Foo {
46
46
* constructor(data) {
47
47
* // Binds all functions from Foo.prototype to 'this',
@@ -60,8 +60,8 @@ export interface Obj extends Object {
60
60
* logit(); // logs [1, 2, 3] from the myFoo 'this' instance
61
61
* ```
62
62
*
63
+ * #### Example:
63
64
* This example creates a bound version of a service function, and copies it to another object
64
- * @example
65
65
* ```
66
66
*
67
67
* var SomeService = {
@@ -82,15 +82,18 @@ export interface Obj extends Object {
82
82
* myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'
83
83
* ```
84
84
*
85
- * @param from The object which contains the functions to be bound
85
+ * @param from The object (or a function that returns the from object) which contains the functions to be bound
86
86
* @param to The object which will receive the bound functions
87
- * @param bindTo The object which the functions will be bound to
87
+ * @param bind The object (or a function that returns the object) which the functions will be bound to
88
88
* @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)
89
89
*/
90
- export function bindFunctions ( from : Obj , to : Obj , bindTo : Obj , fnNames : string [ ] = Object . keys ( from ) ) : Obj {
91
- fnNames . filter ( name => typeof from [ name ] === 'function' )
92
- . forEach ( name => to [ name ] = from [ name ] . bind ( bindTo ) ) ;
93
- return to ;
90
+ export function createProxyFunctions ( from : Obj | Function , to : Obj , bind : Obj | Function , fnNames : string [ ] = Object . keys ( from ) ) : Obj {
91
+ const _from = isFunction ( from ) ? from : ( ) => from ;
92
+ const _bind = isFunction ( bind ) ? bind : ( ) => bind ;
93
+ const makePassthrough = fnName => function proxyFnCall ( ) {
94
+ return _from ( ) [ fnName ] . apply ( _bind ( ) , arguments ) ;
95
+ } ;
96
+ return fnNames . reduce ( ( acc , name ) => ( acc [ name ] = makePassthrough ( name ) , acc ) , to ) ;
94
97
}
95
98
96
99
0 commit comments