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
        • 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
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • 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
  • Basic observer interface
  • Getting an observer of a property
  • Getting an observer of an expression

Was this helpful?

Export as PDF
  1. Getting to know Aurelia
  2. Observation

Using observerLocator

The Observer Locator API allows you to watch properties in your components for changes without the need for using the @observable decorator. In most cases, manual observation will not be required using this API, but it is there if you want it.

Basic observer interface

By default, an observer locator is used to create observers and subscribe to them for change notification.

A basic observer has the following interface:

interface IObserver {
  subscribe(subscriber)
  unsubscribe(subscriber)
}

The subscribe method of an observer can be used to subscribe to the changes that it observes. This method takes a subscriber as its argument.

A basic subscriber has the following interface:

interface ISubscriber {
  handleChange(newValue, oldValue)
}

Getting an observer of a property

An observer of an object property can be retrieved using an observer locator.

An example of this is:

// getting the observer for property 'value'
const observer = observerLocator.getObserver(obj, 'value')

And to subscribe to changes emitted by this observer:

const subscriber = {
  handleChange(newValue) {
    console.log('new value of object is:', newValue)
  }
}

observer.subscribe(subscriber)

// and to stop subscribing
observer.unsubscribe(subscriber)

Getting an observer of an expression

It's not always sufficient to observe a single property on an object, and it's sometimes more desirable to return a computed value from the source so that subscribers of an observer don't have to perform any logic dealing with the updated values. An example of this is the follow observation of firstName and lastName to notify full name:

const obj = { firstName: '', lastName: '' }
function notifyFullnameChanged() {
  console.alert(`${obj.firstName} ${obj.lastName}`);
}
const observer1 = observerLocator.getObserver(obj, 'firstName').subscribe({ handleChange: notifyFullnameChanged })
const observer2 = observerLocator.getObserver(obj, 'lastName').subscribe({ handleChange: notifyFullnameChanged })

Doing it the way above is cumber some as we need to setup 2 observers and 2 subscribers, also there's a typo risk. We can also use a getter to express a computed value, and then observe that getter to avoid having to do heavy setup work:

const obj = { firstName: '', lastName: '', get fullName() { return `${this.firstName} ${this.lastName}` } }
const observer = observerLocator.getObserver(obj, 'fullName').subscribe({ handleChange: fullname => alert(fullname) });

This is not always feasible since the obj could be from a 3rd party library, or some json data from server, and the risk of having a typo fullName is still there.

Aurelia provides another API of creating observer to deal with this scenario, where it's more desirable to use a function/lambda expression to express the dependencies and computed value to notify the subscriber. To use this API, replace the 2nd parameter of getObserver with a getter function to express the value:

const obj = { firstName: '', lastName: '' }
const observer = observerLocator.getObserver(obj, obj => `${obj.firstName} ${obj.lastName}`).subscribe({
  handleChange: fullname => alert(fullname)
});
PreviousHTML observationNextWatching data

Last updated 2 years ago

Was this helpful?

Sometimes it's more desirable to work with a higher level API, for this consider using

watch