使用RxJS模拟命令队列和撤消堆栈

Simulating a command queue and undo stack with RxJS

本文关键字:撤消 堆栈 队列 命令 RxJS 模拟 使用      更新时间:2023-09-26

我正在尝试使用RxJS复制这个演示。演示是一个小型应用程序,用户可以在其中控制机器人。机器人可以向前或向后移动,向左或向右旋转,并拾取或放下物品。用户可以对命令(如"前进"、"旋转")进行排队,当用户单击"执行"按钮时,队列中的命令就会执行。用户还可以撤消已经执行的命令

传统上,使用尚未执行的命令的队列可以很容易地实现此应用程序。执行的命令被推入堆栈,每当按下撤消按钮时,顶部命令就会弹出并撤消。

我可以通过以下操作"收集"命令并执行它们:

var id = 0;
var add = Rx.Observable.fromEvent($("#add"), 'click').map(function(){
  var ret = "Command_"+id;
  id++;
  return ret
})
var invoke = Rx.Observable.fromEvent($("#invoke"), 'click')
var invokes = add.buffer(invoke)

buffer()方法将流转换为数组流。我可以订阅调用流并获得命令数组:

invokes.subscribe(function(command_array){...})

或者我可以创建一个Rx.Subject(),在那里我只需逐个推送命令:

var invoked_commands = new Rx.Subject()
invokes.subscribe(function(command_array){
  for(var i=0; i < command_array.length; i++){
    invoked_commands.onNext(command_array[i])
  }
});
invoked_commands.subscribe(function(command){ ...});

老实说,我不知道哪种方法会更好,但我也不知道这对我现在来说是否太重要了。我一直试图弄清楚如何实现撤销功能,但我完全不知道该怎么做

在我看来,它必须是这样的(对不起格式):

-c1---c2-c3--------->

----------------u----u->("u"=单击撤消按钮)

----------------c3-c2>(从最新到最旧获取命令,调用undo()方法)

所以我的问题有两个:

  1. 我收集命令的方法好吗
  2. 如何实现撤消功能

编辑:我正在比较变革风格和反应风格,我正在使用这两种风格来实现这个演示。因此,我希望尽可能多地使用Rx*功能。

您必须继续维护undo堆栈的状态。我认为你收集命令的方法是合理的。如果您保留Subject,您可以通过对主题进行另一个订阅来将撤消功能与命令执行解耦:

var undoQueue = [];
invoked_commands.subscribe(function (c) { undoQueue.unshift(c); });
Rx.Observable
    .fromEvent($("#undo"), "click")
    .map(function () { return undoQueue.pop(); })
    .filter(function (command) { return command !== undefined; })
    .subscribe(function (command) { /* undo command */ });

编辑:只使用Rx而不使用可变数组。这似乎不必要地复杂,但哦,好吧,它是功能性的。我们使用scan来维护撤消队列,并与当前队列一起发出一个元组,以及是否应该执行撤消命令。我们将已执行的命令与撤消事件合并。执行添加到队列中的命令,撤消从队列中弹出的事件。

var undo = Rx.Observable
    .fromEvent($("#undo"), "click")
    .map(function () { return "undo"; });
invoked_commands
    .merge(undo)
    .scan({ undoCommand: undefined, q: [] }, function (acc, value) {
        if (value === "undo") {
            return { undoCommand: acc.q[0], q: acc.q.slice(1) };
        }
        return { undoCommand: undefined, q: [value].concat(acc.q) };
     })
     .pluck("undoCommand")
     .filter(function (c) { return c !== undefined })
     .subscribe(function (undoCommand) { ... });

我刚刚创建了一些类似的东西,尽管有点复杂。也许这对某人有帮助。

  // Observable for all keys
  const keypresses = Rx.Observable
    .fromEvent(document, 'keydown')
  // Undo key combination was pressed
  //  mapped to function that undoes the last accumulation of pressed keys
  const undoPressed = keypresses
    .filter(event => event.metaKey && event.key === 'z')
    .map(() => (acc) => acc.slice(0, isEmpty(last(acc)) && -2 || -1).concat([[]]))
  // a 'simple' key was pressed
  const inputChars = keypresses
    .filter(event => !event.altKey && !event.metaKey && !event.ctrlKey)
    .map(get('key'))
    .filter(key => key.length === 1)
  // the user input, respecting undo
  const input = inputChars
    .map((char) => (acc) =>
      acc.slice(0, -1).concat(
        acc.slice(-1).pop().concat(char)
      )
    ) // map input keys to functions that append them to the current list
    .merge(undoPressed)
    .merge(
      inputChars
        .auditTime(1000)
        .map(() => (acc) => isEmpty(last(acc)) && acc || acc.concat([[]]))
    ) // creates functions, that start a new accumulator 1 sec after the first key of a stroke was pressed
    .scan(
      (acc, f) => f(acc),
      [[]],
    ) // applies the merged functions to a list of accumulator strings
    .map(join('')) // join string
    .distinctUntilChanged() // ignore audit event, because it doesn't affect the current string