valor-unistore-undo
TypeScript icon, indicating that this package has built-in type declarations

1.0.11 • Public • Published

经典的命令模式, 实现 undo/redo

依赖unistore

如何在react组件中使用

react顶级组件中增加一个 commandManager 属性, 绑定store 然后可在外部ref.commandManager使用

当然你也可以使用 controller 钩子, 把 commandManager 暴露出去.

具体使用方法:

详细参见 index.test.ts

// 第一步: store 及 Command类的 定义
    const store = createStore<{ a: number }>({ a: 1 });

    class Inc_n_Command extends ICommand<{ a: number }> {
      n: number = 0;
      constructor(store, params) {
        super(store, params);
      }

      execute = () => {
        this.do();
      };

      undo = () => {
        store.setState({ a: this.store.getState().a - this.params.n });
      };

      do = () => {
        store.setState({ a: this.store.getState().a + this.params.n });
      };
    }

    const commandManager = new CommandManager(store);

    expect(store.getState().a).toEqual(1);

// 第二步: 使用
    commandManager.execute(Inc_n_Command as any, 2);

    expect(store.getState().a).toEqual(3);
    expect(commandManager.undoStack.length).toEqual(1);
    expect(commandManager.redoStack.length).toEqual(0);

    // 可undo
    commandManager.undo();
    expect(store.getState().a).toEqual(1);
    expect(commandManager.undoStack.length).toEqual(0);
    expect(commandManager.redoStack.length).toEqual(1);

    // 可redo
    commandManager.redo();
    expect(store.getState().a).toEqual(2);
    expect(commandManager.undoStack.length).toEqual(1);
    expect(commandManager.redoStack.length).toEqual(0);

Readme

Keywords

none

Package Sidebar

Install

npm i valor-unistore-undo

Weekly Downloads

2

Version

1.0.11

License

MIT

Unpacked Size

4.36 kB

Total Files

4

Last publish

Collaborators

  • g770728y