Search code examples
typescriptbindhierarchy

typescript and bind with hierarchy


I try to make bind hierarchy so I can easily build some pre-defined actions. Seems that something is just wrong with Action function as it's not really working when binding.

const Action = (channel: string) => {
    return (action: string) => {
        return (payload: object) => {
            return Object.assign({},payload,{channel: channel, action: action});
        };
    };
};

const WeatherAction = Action.bind('weather');
const WeatherActionSub = WeatherAction.bind('sub');
const WeatherActionUnSub = WeatherAction.bind('unsub');

const test = WeatherActionSub({test: 'test'});
console.log(test);

https://jsfiddle.net/cvowrj0y/


Solution

  • Bind's first argument changes the this keyword. You just need to call here, as the function is curried anyway:

    const WeatherAction = Action('weather');
    const WeatherActionSub = WeatherAction('sub');
    const WeatherActionUnSub = WeatherAction('unsub');
    
    const test = WeatherActionSub({test: 'test'});
    console.log(test);
    

    (Valid binding code, which is rather pointless because the call without arguments has to follow:)

    const WeatherAction = Action.bind(null, 'weather')();
    const WeatherActionSub = WeatherAction.bind(null, 'sub')();
    const WeatherActionUnSub = WeatherAction.bind(null, 'unsub')();
    

    If the function were uncurried it would make sense to bind:

    const ActionUncurried = (channel: string, action: string, payload: object) => {
        return Object.assign({},payload,{channel: channel, action: action});
    };
    
    const WeatherAction = ActionUncurried.bind(null, 'weather');
    const WeatherActionSub = WeatherAction.bind(null, 'sub');
    const WeatherActionUnSub = WeatherAction.bind(null, 'unsub');
    
    const test = WeatherActionSub({test: 'test'});
    console.log(test);