Skip to content

Instantly share code, notes, and snippets.

@tmedwards
Last active February 16, 2021 02:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmedwards/27d2bd49ec8c57eb2391f66f2f86c7bd to your computer and use it in GitHub Desktop.
Save tmedwards/27d2bd49ec8c57eb2391f66f2f86c7bd to your computer and use it in GitHub Desktop.
Very basic example showing how to share state via the context chain
Macro.add('scene', {
tags : null,
handler : function () {
/* Argument sanity checking. */
// Extend our execution context with the `_scene` object so our
// descendants may share state, by looking up our context.
Object.defineProperty(this, '_scene', {
value : /* Whatever you need to share, probably an object. */
});
/* Whatever else the macro needs to do. */
}
});
/*
`<<branch>>` variant that requires a `<<scene>>` be its immediate parent.
*/
Macro.add('branch', {
tags : null,
handler : function () {
// Get our `<<scene>>` parent's shared scene state.
var scene = (function () {
var parent = this.parent;
if (parent === null || parent.name !== 'scene' || !parent.hasOwnProperty('_scene')) {
return null;
}
return parent._scene;
})();
if (scene === null) {
return this.error('must only be used in conjunction with its parent macro <<scene>>');
}
/* Argument sanity checking. */
/* Whatever else the macro needs to do. */
}
});
/*
`<<branch>>` variant that requires a `<<scene>>` be an ancestor.
*/
Macro.add('branch', {
tags : null,
handler : function () {
// Get our first `<<scene>>` ancestor's shared scene state.
var scene = (function () {
var parent = this.contextSelect(function (ctx) {
return ctx.name === 'scene';
});
if (parent === null || !parent.hasOwnProperty('_scene')) {
return null;
}
return parent._scene;
})();
if (scene === null) {
return this.error('must only be used in conjunction with its parent macro <<scene>>');
}
/* Argument sanity checking. */
/* Whatever else the macro needs to do. */
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment