Aurelia Data-binding Strategies - with and if

Overview

When using Aurelia many times I find myself wanting to bind to data that doesn't exist yet. An example of this might be wanting to show a users' role name but role is an optional property of a user.

export class UserViewModel {  
  user = new User();
  makeAdmin() {
    this.user.role = { name: 'Admin' };
  }
}
class User {  
  firstName = 'Wade';
  lastName = 'Watts';
  role;
}

and a view -

<template>  
  <h1>${ user.firstName + ' ' + user.lastName }</h1>
  <h2>${ user.role.name }</h2>
</template>  

The problem is this will fail if the user doesn't yet have a role.

Binding options

The two ways I prefer to tackle this issue are with using the with or the if bindings. Using these we can defer the binding of the user.role properties until the role has a valid value.

Simple examples -

with -

<template>  
  <h1>${ user.firstName + ' ' + user.lastName }</h1>
  <h2 with.bind="user.role">${ name }</h2>
</template>  

if -

<template>  
  <h1>${ user.firstName + ' ' + user.lastName }</h1>
  <h2 if.bind="user.role">${ user.role.name }</h2>
</template>  

As you can see when using the with binding we end up with slightly less code.

An alternative is to use a ternary operator but I try not to use this too much in my view code -

${ user.role ? user.role.name : '' }

With binding

The with binding is really nice because it adds a context to our current node and the children of that node. It will scope any subsequent bindings to that context. Using this we can prevent using user. all over the place and instead with.bind="user" so that all subsequent bindings are bound to that context.

If binding

If is nice as well. The main difference between if and show is that show will simply hide the elements in the DOM where if will completely remove them. This can be important to understand if you are trying to manipulate a DOM node that isn't there because of the if binding.

Feedback

I hope this helps a bit, let me know what you think below!