是否存在此模式的名称,您可以在其中存储返回回调的回调?

时间:2016-08-02 02:58:57

标签: javascript angularjs typescript callback redux

我正在尝试从教程中学习Redux / Angular,并想知道我刚刚开始理解这个模式是否有名称。

这是完整的文件描述,但我试图识别的模式是通过这些行之间的连接:

使用subscribe方法并传入回调函数():

let unsub = SUPER_STORE.subscribe(()=> {
    console.log('subs : ', SUPER_STORE.getState())
});

Subscribe方法推送一个监听器并返回一个回调以删除监听器:

subscribe(listener: ListenerCallback): UnsubscribeCallback {
    this._listeners.push(listener);

    return () => { // returns an "unsubscribe" function
        this._listeners = this._listeners.filter(l => l !== listener);
    };
}

dispatch方法通过循环遍历集合中的每个_listeners来处理这些回调。

this._listeners.forEach((listener: ListenerCallback) => listener());

我从来没有见过这种传递回调函数的模式,它会返回一个新的回调以便以后调用。

问题:

这个模式有名字吗?如果是的话,它是什么?

完全JS:

interface Action {
    type: string;
    payload?: any;
}

interface Reducer<T> {
    (state:T, action:Action): T
}

interface ListenerCallback {
    (): void;
}

interface UnsubscribeCallback {
    (): void;
}


class Store<T> {
    private _state:T;
    private _listeners: ListenerCallback[] = [];

    constructor(private reducer:Reducer<T>, initState) {
        this._state = initState;
    }

    getState():T {
        return this._state;
    }

    dispatch(action: Action): void {
        this._state = this.reducer(this._state, action);
        this._listeners.forEach((listener: ListenerCallback) => listener());
    }

    subscribe(listener: ListenerCallback): UnsubscribeCallback {
        this._listeners.push(listener);
        return () => { // returns an "unsubscribe" function
            console.log('unsubscribe');
            this._listeners = this._listeners.filter(l => l !== listener);
        };
    }
}



const SUPER_REDUCE:Reducer<number> = (state:number, action:Action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        default:
            return state;
    }
};

const INCREMENT_ACTION:Action = {type: 'INCREMENT'};

const SUPER_STORE = new Store<number>(SUPER_REDUCE, 0);

let unsub = SUPER_STORE.subscribe(()=> {
    console.log('subs : ', SUPER_STORE.getState())
});

SUPER_STORE.dispatch(INCREMENT_ACTION); // 0
SUPER_STORE.dispatch(INCREMENT_ACTION);  // 1
SUPER_STORE.dispatch(INCREMENT_ACTION);  // 2
SUPER_STORE.dispatch(INCREMENT_ACTION);  // 4

unsub(); // 'unsubscribe'

1 个答案:

答案 0 :(得分:1)

Pubsub(发布者 - 订阅者模式) https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern