Scoped Variables

Scoped variables are declared inside an <a-xxxx></a-xxxx> element in a <let></let> block, and initialized after the block. The variable name must contain a dot . or be an object if the name doesn't contain a dot. Scoped variables in a.js allow developers to manage reactivity at different levels:

Types of Scoped Variables

  1. Global Scoped Variables

    • Accessible across all <a-xxxx> elements.
    • Declared with global.
    • Example:
      <let>
        global g.variable;
      </let>
      g.variable = "value"
      
  2. Namespace Scoped Variables

    • Shared only among elements with the same namespace attribute value.
    • Declared with nsGlobal.
    • Example:
      <let>
        nsGlobal ns.variable;
      </let>
      ns.variable = ["value1",2,3]
      
  3. Descendant Scoped Variables

    • Shared among elements that are descendants of the element.
    • Declared with dGlobal. Usually in a <a-tagDef forTag="my-ancestor"> element
    • Example:
      <let>
        dGlobal d.variable;
      </let>
      d.variable = { name : "value" }
      
  4. Ancestor Scoped Variables

    • Looks for variables declared in ancestor elements and shares them with child elements.
    • Declared with aGlobal. Usually in a <a-tagDef forTag="my-descendant"> element
    • Example:
      <let>
        aGlobal d.variable;
      </let>
      //here, in the scope, d.variable has the value { name : "value" } as long as the element in inside a `<my-ancestor><my-ancestor>`
      
  5. Local Scoped Variables

    • Restricted to a single <a-xxxx> element.
    • Declared with local.
    • Example:
      <let>
        local l.variable;
      </let>
      l.variable = 3
      

Example Usage

<a-closure>
  <let>
    global g.value;
    nsGlobal ns.value;
    dGlobal d.value;
    aGlobal a.value;
    local l.value;
  </let>

  watch(() => {
    console.log('Global:', g.value);
    console.log('Namespace:', ns.value);
    console.log('Descendant:', d.value);
    console.log('Ancestor:', a.value);
    console.log('Local:', l.value);
  });
</a-closure>

Initialization of variables

Initialize the variables after the closing </let>of the declaration.

Watched variables

Any variable having the keyword watched between the type (global,...) and it's name.

Example

<a-closure>
  <let>
    global watched global.value;
  </let>
  global.value = 42;
</a-closure>

> Advanced functionalities