打字稿并与层次结构绑定

typescript and bind with hierarchy

我尝试制作绑定层次结构,以便我可以轻松构建一些预定义的操作。 似乎 Action 函数出了点问题,因为它在绑定时并没有真正起作用。

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/

Bind 的第一个参数更改了 this 关键字。你只需要在这里调用,因为这个函数无论如何都是柯里化的:

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

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

(有效的绑定代码,这毫无意义,因为必须遵循不带参数的调用:)

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

如果函数是非柯里化的,那么绑定是有意义的:

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);