Get the Newsletter

Binding: The Binding Engine

How data-binding works in Aurelia.

Introduction

The binding engine is an utility export of aurelia-binding module, which gives some higher level APIs for dealing with observation, which leverages aurelia binding system primitives under the hood.

How to install

Retrieving an instance of the BindingEngine by injecting it to any of your class inside an Aurelia application:

    
  import { BindingEngine } from 'aurelia-framework'; // or 'aurelia-binding'
  
  export class MyViewModel {
  
    static inject() {
      return [BindingEngine]
    }
  
    constructor(bindingEngine) {
      //
    }
  }
  
  

Note: you can also construct the BindingEngine instance directly, or get it from a container. The example goes with simplest code.

Now let's use it to observe changes on objects (arrays are objects too). Generally, we will use propertyObserver(obj, propertyName) for object property value changes and collectionObserver(collection) for collection mutation.

Observing a property on an object

  • propertyObserver(obj, propertyName) returns a PropertyObserver object, with a public method subscribe that can be used like the following example:
    
    bindingEngine
      .propertyObserver(myObject, 'myObjectPropertyName')
      .subscribe((newValue, oldValue) => {
        // handle value change here
      });
  
  

Observing a collection mutation

  • collectionObserver(collection) returns a CollectionObserver object, with a public method subscribe that can be used like the following example:
    
    bindingEngine
      .collectionObserver(myCollection)
      .subscribe((splice) => {
        // do something with the mutated collection
      })
  
  

splice is an object with ICollectionObserverSplice interface, source code here

Observing an expression on an object

Often times you would want to observe a chain of property accesses (or a path), binding engine also has an API to support this. You can use expressionObserver(obj, expressionString) to create an observer, that will notify you when any property within the path of expressionString has been changed, like the following example:

    
    bindingEngine
      .expressionObserver(this, 'project.name')
      .subscribe((newProjectName, oldProjectName) => {
        // do something with the new project name value
      });