LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Current route
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • Kernel Errors
      • Template Compiler Errors
      • Dialog Errors
      • Runtime HTML Errors
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Understanding state tearing
  • Managing state updates with batch
  • Benefits of using batch

Was this helpful?

Export as PDF
  1. Getting to know Aurelia

Understanding synchronous binding

Aurelia v2 employs a synchronous binding system, which immediately notifies changes as they occur. This approach provides great control and predictability over state changes. However, managing multiple state updates that must be processed together requires careful handling to ensure consistency.

Synchronous binding systems notify changes immediately, providing instant feedback and control. In contrast, asynchronous binding systems queue changes and notify them later, typically in the next microtask or tick, which can help avoid issues like state tearing but introduces other complexities like race conditions (if you worked with Aurelia 1, then you might be familiar with the need to use queueMicroTask to work around this in Aurelia 1).

Understanding state tearing

State tearing occurs when multiple state updates that should be processed together result in premature change notifications and recomputations. This can lead to inconsistent states and application errors. Aurelia v2’s synchronous binding system is particularly prone to this issue.

Consider the following example:

class NameTag {
    firstName = '';
    lastName = '';

    update(first, last) {
        this.firstName = first;
        this.lastName = last;
    }

    @computed()
    get fullName() {
        if (!this.firstName || !this.lastName) {
            throw new Error('Only accepting names with both first and last names');
        }
        return `${this.firstName} ${this.lastName}`;
    }
}

const nameTag = new NameTag();
nameTag.update('John', 'Doe'); // 💥

In this example, updating firstName and lastName simultaneously causes an error. This happens because the synchronous change propagation causes the computed property fullName to be evaluated before both firstName and lastName have been updated.

Managing state updates with batch

Aurelia provides the batch function to handle multiple state updates efficiently. The batch function groups state changes and defer change notifications until all updates within the batch are complete. This ensures that related states are updated together, maintaining consistency.

Here’s how to use the batch function to manage state updates:

import { batch } from 'aurelia';

class NameTag {
    firstName = '';
    lastName = '';

    update(first, last) {
        batch(() => {
            this.firstName = first;
            this.lastName = last;
        });
    }

    @computed()
    get fullName() {
        if (!this.firstName || !this.lastName) {
            throw new Error('Only accepting names with both first and last names');
        }
        return `${this.firstName} ${this.lastName}`;
    }
}

const nameTag = new NameTag();
nameTag.update('John', 'Doe'); // No error

By wrapping the state updates in a batch function, change notifications for firstName and lastName are deferred until both updates are complete. This ensures that the fullName computed property is evaluated with the latest values of firstName and lastName.

Benefits of using batch

  • Consistency: Ensures that all related state changes are processed together, avoiding premature evaluations.

  • Predictability: Maintains the predictable nature of the synchronous binding system by controlling when notifications are sent.

  • Performance: Reduces unnecessary recomputations by grouping state changes.

Aurelia’s synchronous binding system provides immediate change notifications, offering great control over state updates. Using the batch function, developers can efficiently manage multiple state updates, ensuring consistency and predictability in their applications. Proper use of batch enhances the robustness of Aurelia applications, making state management more reliable and efficient.

PreviousTemplate controllersNextDynamic composition

Last updated 11 months ago

Was this helpful?