Skip to content

Commit

Permalink
fixes discardAllChanges() when using @filter()
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed Jan 14, 2020
1 parent 5c9248b commit 3760478
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@colyseus/schema",
"version": "0.5.22",
"version": "0.5.23",
"description": "Schema-based binary serializer / de-serializer.",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
8 changes: 5 additions & 3 deletions src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -722,11 +722,13 @@ export abstract class Schema {

discardAllChanges() {
const schema = this._schema;
const changes = this.$changes.changes;
const changes = Array.from(this.$changes.changes);
const fieldsByIndex = this._fieldsByIndex;

for (const field in changes) {
for (const index in changes) {
const field = fieldsByIndex[index];
const type = schema[field];
const value = changes[field];
const value = this[field];

// skip unchagned fields
if (value === undefined) { continue; }
Expand Down
33 changes: 31 additions & 2 deletions test/ChangeAPITest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as sinon from "sinon";
import * as util from "util";
import * as assert from "assert";

import { type } from './../src/annotations';
import { type, filter } from './../src/annotations';
import { State, Player } from "./Schema";
import { Schema, MapSchema, ArraySchema, DataChange } from "../src";

Expand Down Expand Up @@ -658,6 +658,36 @@ describe("Change API", () => {
});
});

describe("with filters", () => {
class Round extends Schema {
@type(["number"]) scores = new ArraySchema<number>(0, 0);
}

class State extends Schema {
@filter(() => true)
@type("number") timer: number;
@type(Round) currentRound: Round = new Round();
}

it("should not trigger unchanged fields", () => {
let changesTriggered: number = 0;

const state = new State();
state.timer = 10;

const decodedState = new State();
decodedState.currentRound.listen("scores", () => changesTriggered++);

do {
state.timer--;
decodedState.decode(state.encodeFiltered({}));
state.discardAllChanges();
} while (state.timer > 0);

assert.equal(1, changesTriggered);
});
});

describe("triggerAll", () => {
it("should trigger onChange on Schema instance", () => {
const state = new State();
Expand Down Expand Up @@ -701,7 +731,6 @@ describe("Change API", () => {
});
});


describe("callback order", () => {
class MyState extends Schema {
@type("string") str: string;
Expand Down

0 comments on commit 3760478

Please sign in to comment.