hyperscript

variables scopes in _hyperscript js


I am having a hard time understanding the variable declaration in _hyperscript from the docs https://hyperscript.org/docs/#scoping

element scope variable should work inside that element for example

<div _="set :x to 10">
<button _="on click increment :x by 25 then put it into the next <output/>">
  call inc :x
</button>
<output></output>
<button _="on click decrement :x by 25 then put it into the previous <output/>">
  call dec :x
</button>
</div>

I want to achieve a increment and decrement counter which modified the variable x by clicking the respective button but instead each button creates its own element scoped variable x.


Solution

  • Element-scoped variables (declared with :, or top-level set) will be shared across handlers on an element

    Ref: https://github.com/bigskysoftware/_hyperscript/issues/360#issuecomment-1203743221

    This means that the local or element variable is only shared within that element. It will not be available in any of the children element.

    To resolve your issue, you can either define the whole logic in the parent element, use global or use attributes for better readability.

    Example using attributes:

    <div _="on load set @my-attr to 10" id="foo">
        <button _="on click increment #foo's @my-attr by 25 then put it into the next <output/>">
    call inc :x
        </button>
        <output></output>
        <button _="on click decrement #foo's @my-attr by 25 then put it into the previous <output/>">
    call dec :x
        </button>
    </div>