Skip to main content

Data Attribute

The $data attribute is a feature that allows you to initialize reactive data directly in your HTML template.

Basic Usage

  • Add the $data attribute to an HTML element, typically the root element of your application.
  • Set the value of $data to a JSON string containing key-value pairs representing your initial data.

Example

index.html
<div $data='{"count": 0, "message": "Hello, World!"}'>
<!-- Your app content here -->
</div>

How it Works

  • The framework scans the document for elements with the $data attribute.
  • It parses the JSON string provided in the $data attribute.
  • For each key-value pair in the parsed data: The framework creates a corresponding property in the global $ object. These properties are made reactive, meaning changes to them will trigger updates in the UI.

Advanced Usage

Multiple Data Properties

index.html
<div $data='{"user": {"name": "John", "age": 30}, "isLoggedIn": true}'>
<!-- Your app content here -->
</div>

Combining with Other Reactive Features

Once initialized, you can use these data properties with other reactive features of the framework, such as $text:

index.html
<div $data='{"greeting": "Hello"}'>
<p $text="{greeting}, user!"></p>
</div>

Error Handling

If there's an error parsing the JSON in the $data attribute, the framework will log an error to the console. Make sure your JSON is valid to avoid issues.

warning

Limitations

  • The $data attribute should contain valid JSON. Invalid JSON will result in an error and the data won't be initialized.

  • It's generally recommended to use this attribute on a single, top-level element in your application to avoid confusion.

  • Data initialized this way is global to the application (stored in the $ object). Be cautious about naming conflicts if using multiple $data attributes.