Controller store

If you want to store state inside your controller, GreenLight provides you with a reactive store out of the box. All you need to do is get the actual controller and use the $store attribute.

const MyController = GreenLight.controller("MyController");

MyController.$store.set("github-username", "Petre-Gabriel");

console.log(MyController.$store.get("github-username")); // Petre-Gabriel

// If nothing is specified in the get method, it returns the whole object.
console.log(MyController.$store.get()); // [object Object]

Controller Effect

Each controller has an effect method to react to dependencies changes. Here is an example:

const MyController = GreenLight.controller("MyController");

MyController.effect(() => {
  // This code will run when searchInput or searchFilter changes.
}, ["searchInput", "searchFilter"]);

If multiple variables from the dependencies array change at the same time, the effect will run only once.

MyController.$store.set("searchInput", "apples");
MyController.$store.set("searchFilter", "color=red");

If you run the code above, the effect will be triggered once. That is because internally, GreenLight uses a strategy called debounce to wait for new changes. It waits for a few milliseconds before the final call so if there are multiple changes to the dependency array it will only call it once.

Detect changes

Also, you can react to changes on the global store by using the onChange method provided:

GreenLight.$globalStore.onChange((keyChanged) => {
  // Here you put the code you want to execute on change.
});

keyChanged reperesents the name of the variable that changed

NOTE It can safely be used in the store's set / get function because it can return an object-like text ( myObject.nested.property )

Store effects

This is similar to the onChange method but it only reacts to changes on variables passed in the dependencies array. Here is an example:

GreenLight.$globalStore.effect(() => {
  // This will run only if the isUserConnected variable changed.
}, ["isUserConnected"]);

How it works internally

As of any effect in this library, it utilizes a debounce strategy to batch changes together and only call the effect once if multiple variables have changed at once.

Table Content