Skip to content

Instantly share code, notes, and snippets.

@endel
Created July 17, 2023 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save endel/4ca35460b15a272f0e42607f2b70e656 to your computer and use it in GitHub Desktop.
Save endel/4ca35460b15a272f0e42607f2b70e656 to your computer and use it in GitHub Desktop.
Colyseus Schema - Listen for all changes and print them as they come
room.onStateChange.once(function() {
function registerCallbacksOnStructure (schemaInstance, path) {
const schema = schemaInstance['_definition'].schema;
for (let field in schema) {
const schemaType = typeof(schema[field]);
if (schemaType === "object") {
// on item added to collection
schemaInstance[field].onAdd(function (item, key) {
onItemAdd([...path, field], item, key);
});
// on item removed from collection
schemaInstance[field].onRemove(function (item, key) {
onItemRemove([...path, field], item, key);
});
// on item changed in collection
schemaInstance[field].onChange(function (item, key) {
onItemChange([...path, field], item, key);
});
} else if (schemaType === "function") {
// direct schema instance
schemaInstance[field].onChange(function () {
onChangeAtPath(field, path, schemaInstance[field], undefined);
});
// created the schema instance
onChangeAtPath(field, path, schemaInstance[field], undefined);
} else {
// field on schema instance
schemaInstance.listen(field, function (value, previousValue) {
onChangeAtPath(field, path, value, previousValue);
});
}
}
}
function onChangeAtPath (key, path, value, previousValue) {
console.log("onChange", [...path, key].join("."), { key, value, previousValue });
}
function onItemAdd (path, instance, key) {
// only register callbacks on child Schema structures.
if (instance['_definition']) {
registerCallbacksOnStructure(instance, [...path, key]);
}
console.log("onAdd", [...path, key].join("."), instance);
}
function onItemChange (path, instance, key) {
console.log("onChange", [...path, key].join("."), instance);
}
function onItemRemove (path, instance, key) {
console.log("onRemove", [...path, key].join("."), instance);
}
registerCallbacksOnStructure(self.room.state, []);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment