HTML behaviors

HTML behaviors in Aurelia allow you to extend HTML with reusable, encapsulated functionality. They come in two primary forms: Custom Elements and Custom Attributes. Understanding these behaviors is fundamental to creating modular, maintainable Aurelia applications.

Understanding HTML Behaviors

HTML behaviors enable you to:

  • Create reusable UI components

  • Encapsulate complex functionality

  • Extend existing HTML elements with new capabilities

  • Build a library of domain-specific components

The Two Types of HTML Behaviors

Custom Elements

Custom elements create entirely new HTML elements with their own templates, view-models, and behavior.

<!-- Custom element usage -->
<user-profile user.bind="currentUser"></user-profile>
<data-grid items.bind="products" columns.bind="gridColumns"></data-grid>

Custom Attributes

Custom attributes add behavior to existing HTML elements without changing their fundamental nature.

Creating HTML Behaviors

Naming Conventions

Aurelia follows consistent naming conventions for HTML behaviors:

JavaScript/TypeScript Class Names:

  • Use PascalCase with descriptive suffixes

  • Custom Elements: UserProfileCustomElement or just UserProfile

  • Custom Attributes: TooltipCustomAttribute or just Tooltip

HTML Usage:

  • Automatically converted to kebab-case

  • UserProfile becomes <user-profile>

  • TooltipCustomAttribute becomes tooltip="..."

Resource Registration

There are multiple ways to make HTML behaviors available in your application:

Local Registration (Per-Template)

Global Registration

Feature-Based Registration

Custom Element Fundamentals

Basic Custom Element Structure

user-card.js

user-card.html

Custom Element with Content Projection

modal-dialog.html

Usage:

Custom Attribute Fundamentals

Simple Custom Attribute

highlight.js

Usage:

Multi-Property Custom Attribute

border-style.js

Usage:

Lifecycle Integration

Custom Element Lifecycle

Custom Attribute Lifecycle

Advanced HTML Behavior Patterns

Behavior Composition

Combine multiple behaviors for powerful functionality:

Behavior Inheritance

Dynamic Behavior Loading

Integration with Dependency Injection

Injecting Services into Behaviors

Behavior-Specific Services

Testing HTML Behaviors

Unit Testing Custom Elements

Testing Custom Attributes

Performance Considerations

Efficient Behavior Creation

Memory Management

Best Practices

1. Single Responsibility

Each behavior should have one clear purpose:

2. Consistent Naming

Follow consistent naming patterns:

3. Proper Lifecycle Usage

Use appropriate lifecycle hooks:

4. Bindable Property Design

Design bindable properties thoughtfully:

HTML behaviors are the foundation of component-based architecture in Aurelia. By understanding both custom elements and custom attributes, you can create powerful, reusable functionality that makes your applications more maintainable and scalable.

Last updated

Was this helpful?