Skip to content Skip to sidebar Skip to footer

Handling External Function Imports

This might be a rather general question on how to handle imports of external functions and exporting functions. So I have a component like this: import React, {Component} from 'r

Solution 1:

One could import multiple methods at once like this:

import * as path from"./path";

classFoo { }

Then we can assign them as static methods:

Object.assign( Foo, path );

or as prototype methods:

Object.assign( Foo.prototype, path );

If you want to bind the context its a bit more difficult. That could be done in the constructor:

import * as path from"./path";

classFoo { 
  constructor(){
    for(var key in path) this[key] = path[key].bind(this);
  }
  //...
}

Or if you just want a few functions to be bound ( maybe faster ) :

import * as path from"./path";

classFoo { 
  constructor(){
    const bind = ["onClick","onResize"/* whatever*/];
    for(var key of bind) this[key] = this[key].bind(this);
  }
}

Object.assign(Foo, path.prototype);

Solution 2:

as an alternative design, you may consider a mixin, eg something like:

letclickable = (superclass) => classextends superclass {  

    constructor(props) { super(props); };

    handleClick = () => { console.log( "clicked ", this ); };
};

classFooextendsclickable(Component) {
    constructor(props) { super(props); this.state = { ... };};

    render() { return<divonClick={this.handleClick}>foobar</div>; }
}   

Post a Comment for "Handling External Function Imports"