【问题标题】:Is there a name for this pattern where you store a callback that returns a call back?这种模式是否有一个名称,您可以在其中存储返回回调的回调?
【发布时间】:2016-08-02 02:58:57
【问题描述】:

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

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

使用订阅方法并传入一个回调函数():

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 方法通过遍历集合中的每个 _listener 来处理这些回调。

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'

【问题讨论】:

  • 发布/订阅?每次处理事件时

标签: javascript angularjs typescript callback redux


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    相关资源
    最近更新 更多