refactor: better context creation API

This commit is contained in:
cha0s 2019-09-08 06:04:31 -05:00
parent 6b124ab183
commit d9004f0e5a
4 changed files with 20 additions and 12 deletions

View File

@ -11,16 +11,19 @@ const debug = D('@avocado:behavior:context');
export class Context {
constructor() {
constructor(defaults = {}) {
this.map = new Map();
this.addDefaults();
this.addGlobalDefaults();
for (const key in defaults) {
this.add(key, defaults[key]);
}
}
add(key, value) {
this.map.set(key, value);
}
addDefaults() {
addGlobalDefaults() {
this.add('context', this);
this.add('Flow', Flow);
this.add('Math', MathExt);
@ -30,7 +33,7 @@ export class Context {
clear() {
this.map.clear();
this.addDefaults();
this.addGlobalDefaults();
}
destroy() {
@ -81,7 +84,9 @@ export class Context {
// Try to set the value.
switch (step.type) {
case 'key':
return node[step.key] = value.get(this);
if ('object' === typeof node) {
return node[step.key] = value.get(this);
}
case 'invoke':
const rendered = this.constructor.renderStepsUntilNow(steps, step);
debug(`invalid assignment to function "${rendered}"`);

View File

@ -32,8 +32,9 @@ export class Behaved extends decorate(Trait) {
constructor(entity, params, state) {
super(entity, params, state);
this._context = new Context();
this._context.add('entity', this.entity);
this._context = new Context({
entity: this.entity,
});
this._currentRoutine = undefined;
const routinesJSON = this.params.routines;
this._routines = (new Routines()).fromJSON(routinesJSON);

View File

@ -63,8 +63,9 @@ export class Alive extends decorate(Trait) {
constructor(entity, params, state) {
super(entity, params, state);
this._context = new Context();
this._context.add('entity', this.entity);
this._context = new Context({
entity: this.entity,
});
const actionsJSON = this.params.deathActions;
this._deathActions = behaviorItemFromJSON(actionsJSON);
this._deathSound = this.params.deathSound;

View File

@ -64,9 +64,10 @@ export class Collider extends decorate(Trait) {
pushActionBundle(paramActions, other) {
const actions = behaviorItemFromJSON(paramActions);
const context = new Context();
context.add('entity', this.entity);
context.add('other', other);
const context = new Context({
entity: this.entity,
other,
});
const bundle = {
actions,
context,