data-* attributes

In Leaf, you are given a structure that will make it easier for you to structured your frontend UI. Leaf does not use a reactivity system or virtual DOM, it uses binding method and a scope system to wrap logic in a specific environment that is marked with data-scope. In Leaf, there are three main attributes: data-scope as a wrapper, data-target as a marker, and data-action as a trigger.

data-scope

data-scope is the primary attribute that wraps logic within a specific environment so you can use data-target and data-action within it. The data-scope value is captured by the defineScope function you write in your js file.

Example HTML

<div data-scope="greeter">
  <!-- your code here -->
</div>

You must define the greeter above using defineScope.

javascript

//scope_greeter.js
import { defineScope } from "https://cdn.jsdelivr.net/gh/Rahmad2830/Leaf@v1.0.0/dist/Leaf.min.js"

//define greeter here
defineScope("greeter", () => {
  //your code here
})

when you enter a scope that does not exist in the data-scope, you will receive an error that the scope does not exist

data-target

data-target is a marker for an element. It’s typically used to retrieve an element and then you’re free to do whatever you want with it. To retrieve it, use the targets keyword in defineScope.

Example HTML

<div data-scope="greeter">
  <div data-target="hello">
    Something here
  </div>
</div>

then to take the hello element we have to use targets

javascript

//scope_greeter.js
import { defineScope } from "https://cdn.jsdelivr.net/gh/Rahmad2830/Leaf@v1.0.0/dist/Leaf.min.js"

//define greeter here
defineScope("greeter", ({ targets /*you need to call targets keyword here first */}) => {
  //use targets keyword
  const hello = targets.hello
  
  console.log(hello)
  //output will be hello element
})

data-action

data-action is a powerful attribute that can execute or trigger an action. It makes your HTML look smarter. Furthermore, data-action doesn’t use eval(), making it very safe to use. Its value uses the event->function format.

Example HTML

<div data-scope="greeter">
  <div data-target="hello" hidden>
    Something here
  </div>
  
  <button data-action="click->toggle">Toggle</button>
</div>

When you define data-action as above, it is automatically connected to the function below.

javascript

//scope_greeter.js
import { defineScope } from "https://cdn.jsdelivr.net/gh/Rahmad2830/Leaf@v1.0.0/dist/Leaf.min.js"

//define greeter here
defineScope("greeter", ({ targets }) => {
  const hello = targets.hello
  
  function toggle() {
    hello.hidden = !hello.hidden
  }
  
  //you need to return the action trigger in this case toggle function
  //its automaticly connected to data-action
  return { toggle }
})

You can invoke multiple triggers at once by adding a space between each action. For example: data-action=“click->toggle click->run”