Skip to content

Instantly share code, notes, and snippets.

@endel
Created December 9, 2016 15:04
Show Gist options
  • Select an option

  • Save endel/66c4e2ce4045eecbb138d41313680140 to your computer and use it in GitHub Desktop.

Select an option

Save endel/66c4e2ce4045eecbb138d41313680140 to your computer and use it in GitHub Desktop.
Colyseus.js feature proposal: better patch handling

In the current client version, you currently need to loop through all incoming patch list, and manually check for interesting messages to handle.

Example from tic-tac-toe

room.onPatch.add(function(patches) {
  for (let i=0; i<patches.length; i++) {
    let patch = patches[i]

    if (patch.op === "add" && patch.path === "/currentTurn") {
      this.nextTurn( patch.value )

    } else if (patch.op === "replace" && patch.path.indexOf("/board") === 0) {
      let [_, x, y] = patch.path.match(/\/board\/(\d)\/(\d)/)
      this.board.set(x, y, patch.value)

    } else if (patch.op === "replace" && patch.path === "/winner") {
      this.showWinner(patch.value)
  }
})

The problem here is that the patch handling can easily get out of control. Resulting in a huge if/else block which is difficult to read and maintain.

The proposal is to allow listening to specific events/changes, in a pattern-matching fashion.

Example:

room.onPatch("currentTurn", "add", (value) => {
  this.nextTurn( value );
});

room.onPatch("board/:number/:number", "replace", (x, y, value) => {
  this.board.set(x, y, value);
});

room.onPatch("winner", "replace", () => {
  this.showWinner(value);
});

The new interface would be like this:

onPatch(path: string | string[], operation: string, callback: Function);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment