stimulus-data-bindings
v2.0.0
Published
One-way data binding controller for stimulus.js
Readme
Stimulus Data Bindings
Stimulus controller to provide one-way data bindings from form input.
Automatically sets bindings on connection to the DOM, and can perform updates
on any event via a data-action attribute.
Installation
$ yarn add stimulus-data-bindingsUsage
Register the controller with Stimulus:
// application.js
import { Application } from "@hotwired/stimulus";
import DataBindingController from "stimulus-data-bindings";
const application = Application.start();
application.register("data-binding", DataBindingController);Initialize the controller on a container element, then add bindings:
<div data-controller="data-binding">
<form>
<input
type="text"
data-action="change->data-binding#update"
data-binding-target="output"
data-binding-property="textContent"
data-binding-value="$source.value"
data-binding-debug="true"
/>
</form>
<div class="output">
<div data-binding-ref="output" />
</div>
</div>All input elements to be bound require at least a data-action calling the
update method, a data-binding-target specifying the target element, and either a data-binding-property to set a property on the target, or a data-binding-attribute to set an attribute.
Optionally data-binding-condition can be passed, to only set the property/attribute if the condition evaluates to true. Also data-binding-value can be passed, to set the value of the target property/attribute.
multiple properties and attributes can be used separated by a space, as well as multiple targets.
Most data attributes (property, attribute, value, and condition) can be set on the target. When set on both the target and the source, target will override the source.
Options
data-binding-debug
e.g: data-binding-debug="true"
Set this to true to have helpful debug information logged to the console. We strongly recommend having this switched on when setting up your bindings, then set to false or remove when you're happy its working.
data-binding-target
e.g: data-binding-target="my-target"
The target element(s) to alter. any element that has a data-binding-ref of this value will match. Multiple elements can match.
data-binding-property
e.g: data-binding-property="textContent"
The property(s) of the target element to set.
Security Note: Only safe properties are allowed. Dangerous properties like innerHTML, outerHTML, onclick, src, href, and any property starting with on are automatically blocked to prevent XSS attacks. See the Security section for allowed properties.
data-binding-attribute
e.g: data-binding-attribute="disabled hidden"
The attribute(s) of the target element to set.
Security Note: Only safe attributes are allowed. Dangerous attributes like onclick, onerror, src, href, and any attribute starting with on are automatically blocked to prevent XSS attacks. All data-* attributes are allowed. See the Security section for allowed attributes.
data-binding-class
e.g: data-binding-class="text-red-500 line-through"
The classes to be added/removed from the target element.
data-binding-value
e.g: data-binding-value="$source.value"
The value to set the target attribute/property to. Note that this field evaluates an expression, this expression has access to $source (the element this is defined on) and $target (the target element).
If you would like to pass in a string, you would have to do this: data-binding-value="'my string'".
If this value is not set, the attribute will be set/removed without a value.
data-binding-condition
e.g: data-binding-condition="$source.value === 'hello world'"
The condition to check whether or not to set the target attribute/property/class. This evaluates an expression which has access to the value of the source element as $source and the target element as $target.
Expression Syntax
Both data-binding-value and data-binding-condition support JavaScript-like expressions. Here's what's available:
Variables
$source- The source element (the element where the binding is defined)$target- The target element (the element that will be modified)
Property Access
You can access properties and attributes of elements using dot notation:
$source.value- The value of an input, textarea, or select element$source.checked- The checked state of a checkbox or radio input$source.dataset.foo- Access data attributes (e.g.,data-foo="bar"becomes$source.dataset.foo)$target.dataset.id- Access target element's data attributes
Comparison Operators
===- Strict equality!==- Strict inequality>- Greater than<- Less than>=- Greater than or equal<=- Less than or equal
Logical Operators
&&- Logical AND||- Logical OR!- Logical NOT (negation)
Literals
- Strings: Use single or double quotes -
'hello'or"world" - Numbers:
5,3.14,-10 - Booleans:
true,false - Null/Undefined:
null,undefined
Template Literals
You can use template literals (backticks) in data-binding-value to create dynamic strings:
data-binding-value="`Hello ${$source.value}!`"Parentheses
Use parentheses to group expressions and control evaluation order:
data-binding-condition="($source.value === 'a' || $source.value === 'b') &&
$source.checked"data-binding-initial (Defaults to true)
e.g: data-binding-initial="true"
e.g: data-binding-initial="false"
If this is true data-binding#update will be called on load to set an initial value. Set to false to prevent this behaviour.
data-binding-event
e.g: data-binding-event="change input"
You can set one or more events to be triggered when the data-binding-property is changed. This is sometimes required because programmatically assigned values do not trigger events on an element, whereas physically updating the value in the UI does.
- Note events will not be triggered on changes to
data-binding-attribute. Only property changes will trigger an event.
Examples
Mirror and alter the contents of an input field
<input
type="text"
data-action="change->data-binding#update"
data-binding-target="foo"
data-binding-property="textContent"
data-binding-value="`edited-${$source.value}`"
/>
<div data-binding-ref="foo"><!-- this will be edited-xxx --></div>Set a data attribute of an element if a number box has a value greater than 5
<input
type="number"
data-action="change->data-binding#update"
data-binding-target="foo"
data-binding-condition="$source.value > 5"
data-binding-attribute="data-large"
/>
<!-- this will have data-large set only if the input has a number greater than 5 in it -->
<div data-binding-ref="foo"></div>Toggle a class on a div based on if a checkbox is checked
<input
type="checkbox"
data-action="change->data-binding#update"
data-binding-target="foo"
data-binding-condition="$source.checked"
data-binding-class="badger bodger"
/>
<!-- this will have the classes "badger" and "bodger" when the checkbox is checked, and not if it is unchecked. -->
<div data-binding-ref="foo"></div>Disable and hide a field if a checkbox is not checked
<input
type="checkbox"
data-action="change->data-binding#update"
data-binding-target="foo"
data-binding-condition="!$source.checked"
data-binding-attribute="disabled hidden"
/>
<!-- this will be visable and enabled only if the checkbox is ticked -->
<div data-binding-ref="foo"></div>Hide one field, and disable another, based on whether a checkbox is checked
<input
type="checkbox"
data-action="change->data-binding#update"
data-binding-target="foo"
/>
<div
data-binding-ref="foo"
data-binding-condition="!$source.checked"
data-binding-attribute="disabled"
>
I will be disabled when checked
</div>
<div
data-binding-ref="foo"
data-binding-condition="$source.checked"
data-binding-attribute="hidden"
>
I will be hidden when unchecked
</div>Only show a single field from a list based on the value of a select
<select
data-action="change->data-binding#update"
data-binding-condition="$source.value !== $target.dataset.id"
data-binding-target="bar"
data-binding-attribute="hidden"
>
<option value="1" selected>ID: 1</option>
<option value="2">ID: 2</option>
</select>
<div>
<div data-binding-ref="bar" data-id="1"><!-- currently shown --></div>
<div data-binding-ref="bar" data-id="2"><!-- currently hidden --></div>
</div>Show/Hide elements based on a radio input
<label>B</label>
<input
type="radio"
value="A"
checked
data-action="change->data-binding#update"
data-binding-target="radio"
data-binding-attribute="hidden"
data-binding-initial="false"
/>
<label>A</label>
<input
type="radio"
value="B"
data-action="change->data-binding#update"
data-binding-target="radio"
data-binding-attribute="hidden"
data-binding-initial="false"
/>
<div data-binding-ref="radio" data-binding-condition="$source.value !== 'A'">
Showing A
</div>
<div
data-binding-ref="radio"
data-binding-condition="$source.value !== 'B'"
hidden
>
Showing B
</div>Set the value of an input when a button is clicked
<button
data-action="click->data-binding#update"
data-binding-target="amount"
data-binding-property="value"
data-binding-initial="false"
data-binding-value="$source.dataset.fullAmount"
data-full-amount="12.99"
>
Full amount
</button>
<input type="number" data-binding-ref="amount" />Trigger an event when a property is set
<button
data-action="click->data-binding#update"
data-binding-target="amount"
data-binding-property="value"
data-binding-initial="false"
data-binding-value="$source.dataset.fullAmount"
data-full-amount="12.99"
data-binding-event="change input"
>
Full amount
</button>
<input type="number" data-binding-ref="amount" />Security
This library is designed with security in mind and implements several protections against XSS (Cross-Site Scripting) attacks:
CSP Compliance
✅ Content Security Policy (CSP) Compliant: The library does not use eval(), Function(), or any other dynamic code execution methods. It uses a custom expression parser that is safe even with strict CSP policies.
Property and Attribute Whitelisting
The library uses a whitelist approach to prevent XSS attacks:
Allowed Properties
The following properties are safe to use with data-binding-property:
textContent- Safe text contentvalue- Form input valueschecked- Checkbox/radio statedisabled- Disabled statereadOnly- Read-only statehidden- Visibility statetabIndex- Tab orderariaLabel,ariaHidden,ariaExpanded,ariaChecked,ariaDisabled,ariaSelected- ARIA attributesariaValueText,ariaValueNow,ariaValueMin,ariaValueMax- ARIA value attributes
Blocked Properties
The following properties are blocked for security:
innerHTML,outerHTML,insertAdjacentHTML- Can inject scriptsonclick,onerror,onload, etc. - Event handlerssrc,href,action- Can execute JavaScript via URLs- Any property starting with
on- Event handlers - Any property containing
HTML- HTML manipulation
Allowed Attributes
The following attributes are safe to use with data-binding-attribute:
hidden- Visibilitydisabled,readonly- Form statestabindex- Tab orderrole- ARIA rolearia-label,aria-hidden,aria-expanded,aria-checked,aria-disabled,aria-selected- ARIA attributesaria-valuetext,aria-valuenow,aria-valuemin,aria-valuemax- ARIA value attributes- All
data-*attributes - Any attribute starting withdata-is allowed
Blocked Attributes
The following attributes are blocked for security:
onclick,onerror,onload, etc. - Event handlerssrc,href,action- Can execute JavaScript via URLsstyle- Can inject CSS that executes JavaScript (in some contexts)- Any attribute starting with
on- Event handlers
Security Best Practices
Never trust user input: Even though the library blocks dangerous properties/attributes, always validate and sanitize user input on the server side.
Use safe properties: Prefer
textContentoverinnerHTMLfor displaying user content.Validate expressions: The library validates expressions at initialization, but always review your
data-binding-valueanddata-binding-conditionexpressions.Monitor console errors: The library logs security violations to the console. Monitor these in development and production.
Keep dependencies updated: Regularly update this library and other dependencies to receive security patches.
Reporting Security Issues
If you discover a security vulnerability, please report it responsibly. Do not open a public issue. Instead, contact the maintainers privately.
Contributing
Fork the project.
Install dependencies
$ yarn installStart the test watcher
$ yarn test:watchRunning one-off test runs can be done with:
$ yarn testWrite some tests, and add your feature. Send a PR.
