Tutorial 1 - Completed

Behavior Graph Tutorial 1

by slevin11

JavaScript

import * as bg from "https://cdn.skypack.dev/behavior-graph";

let g = new bg.Graph();

class HelloExtent extends bg.Extent {
  constructor(graph) {
    super(graph);

    this.person = this.state("Nobody");
    this.greeting = this.state("Greetings");
    this.button = this.moment();
    this.message = this.state(null);
    this.sentMessage = this.moment();
    this.loggingEnabled = this.state(true);
    this.behavior()
      .supplies(this.message, this.sentMessage)
      .demands(this.person, this.greeting, this.button)
      .runs(() => {
        this.message.update(this.greeting.value + ", " + this.person.value + "!");
        if (this.button.justUpdated) {
          console.log(this.message.value);
          this.sentMessage.update();
        }
      });

    this.behavior()
      .demands(this.message, this.sentMessage, this.loggingEnabled)
      .runs(() => {
        if (this.loggingEnabled.value) {
          if (this.message.justUpdated) {
            console.log("Message changed to: " + this.message.value + " : " + this.message.event.timestamp);
          }
          if (this.sentMessage.justUpdated) {
            console.log("Message sent: " + this.message.value + " : " + this.message.event.timestamp);
          }
        }
      });


  }
}

let e = new HelloExtent(g);

e.addToGraphWithAction();

g.action(() => {
  e.person.update("World");
  e.greeting.update("Hello");
});
g.action(() => {
  e.greeting.update("Goodbye");
});
g.action(() => {
  e.button.update();
  e.greeting.update("Nevermind");
  e.loggingEnabled.update(false);
});