Custom attributes
Custom attributes in Aurelia allow you to extend HTML elements with additional functionality. This guide covers various ways to create and use custom attributes.
Creating Custom Attributes
Convention-based Custom Attributes
Aurelia uses naming conventions to recognize custom attributes automatically.
Usage:
Explicit Custom Attributes
Use the @customAttribute
decorator for explicit declaration.
Single Value Binding
By default, custom attributes use a single-value binding.
Usage:
Accessing the Element
Inject the Element
to access the DOM element.
Multi-value Bindable Properties
Use @bindable
for multiple properties.
Usage:
Responding to Bindable Property Changes
Implement *Changed
methods to respond to property changes.
Options Binding
Use options binding for complex configurations.
Usage:
Specifying a Primary Property
Use primaryProperty
for a default property.
Usage:
Lifecycle Hooks
Implement lifecycle hooks for fine-grained control.
Caveats and Considerations
Naming Conflicts
When using convention-based custom attributes, be cautious of naming conflicts with built-in HTML attributes or other libraries.
To avoid conflicts, consider using a prefix or the @customAttribute
decorator with a unique name.
Unexpected Behavior with One-time Bindings
One-time bindings (.one-time
) won't update the attribute if the bound value changes after initial binding.
Use .bind
or .to-view
for values that might change.
Attribute vs. Element Semantics
Custom attributes modify existing elements, while custom elements create new elements. Be mindful of this distinction when deciding between the two.
Case Sensitivity in Templates
Custom attribute names in Aurelia 1 are case-insensitive and follow a specific convention:
Define custom attribute classes using PascalCase, typically with a 'CustomAttribute' suffix.
Use kebab-case in HTML templates when applying the custom attribute.
Aurelia does not automatically convert between different cases.
Usage:
Be aware that using camelCase or PascalCase in templates will not work:
Unbinding and Memory Leaks
Ensure proper cleanup in the unbind()
lifecycle method to prevent memory leaks, especially when working with third-party libraries.
Last updated
Was this helpful?