Advanced custom attributes
Advanced patterns for building custom attributes in Aurelia 2, including template controllers, complex bindings, and performance optimization.
Template Controllers
Basic Template Controller Structure
import { customAttribute, ICustomAttributeController, IViewFactory, IRenderLocation, ISyntheticView } from '@aurelia/runtime-html';
import { resolve } from '@aurelia/kernel';
@customAttribute({
name: 'my-controller',
isTemplateController: true,
bindables: ['value']
})
export class MyController {
public readonly $controller!: ICustomAttributeController<this>;
private readonly factory = resolve(IViewFactory);
private readonly location = resolve(IRenderLocation);
private view?: ISyntheticView;
public value: unknown;
public valueChanged(newValue: unknown): void {
this.updateView(newValue);
}
private updateView(show: boolean): void {
if (show && !this.view) {
this.view = this.factory.create().setLocation(this.location);
this.view.activate(this.view, this.$controller, this.$controller.scope);
} else if (!show && this.view) {
this.view.deactivate(this.view, this.$controller);
this.view = undefined;
}
}
public attaching(): void {
if (this.value) {
this.updateView(true);
}
}
public detaching(): void {
if (this.view) {
this.view.deactivate(this.view, this.$controller);
this.view = undefined;
}
}
}Real-World Example: Visibility Controller
Advanced Template Controller: Loading States
Complex Two-Way Binding Attributes
Bi-directional Data Synchronization
Multi-Value Binding
Performance Optimization Patterns
Lazy Initialization
Batch Updates
Error Handling in Custom Attributes
Graceful Degradation
Validation and Sanitization
Testing Custom Attributes
Unit Testing Template Controllers
Best Practices
1. Resource Management
2. Performance Considerations
3. Error Handling
4. Type Safety
Last updated
Was this helpful?