Data-binding CSS variables
Data-binding CSS variables allow you to dynamically modify the styles of elements and classes in your UI from the backend, which could be useful when you wish to modify a batch of elements and control how they behave. Additionally, you can utilize `the data-bind-style-*` HTML attribute (link to docs) to update a single style at once.
In this community post, we will learn how to mass-update a given style in the whole UI with a single change.
To achieve this behavior in our plugin, we can use our plugin’s feature to create custom attribute handlers with the JavaScript’s `element.style.setProperty` API. As custom data-binding attributes work by supplying a "handler" class to the 'engine.registerBindingAttribute' function, it takes both:
- a string for the name of the custom attribute
- a reference to the "handler" class (CSSVariableHandler, which is responsible for setting the value of the CSS variable
For example, you can consider the following sample implementation on how you can integrate this feature in your UI:
- Create an element with a custom data-bind attribute as so:

-
Create a model that will contain two values - one for the CSS variable we want to update and another one for the value we will use. Additionally, adding a special character such as ‘=’ can help with the parsing of the information:

-
Make a class that will handle the custom attribute logic CSSVariableHandler and implement its update function.

- Create the model and register the custom attribute via the ‘engine.registerBindingAttribute’ function, which takes the attribute name, and a reference to the handler class:

-
Once a value is bound to the given HTML element with the custom attribute, we can update the element’s style by
- calling the ‘element.style.setProperty’ function inside the update function
- passing to it the variable name that was bound ("--customVariable" and "lightblue" in our case)

The ‘update’ function receives input arguments "element," which is the HTML element with the custom attribute and value, which are the two concatenated values from the data-bound classes.
Please sign in to leave a comment.
Comments
0 comments