How to (1): Declare a computed list piped through value converter & binding behavior


#1
  1. Current syntax:
<div
  temporary.from-view="filteredAndSortedItems"
  temporary.bind="items | filter :key | sort :direction "></div>
  1. Future syntax:
<let
  filtered-and-sorted-items.bind="items | filter :key | sort :direction"></let>

Explanation for current syntax:

We are creating 2 bindings in the above snippet to compute filteredAndSortedItems based on items, piped through filter and sort value converters, which are quite common when you have a list.

The first binding:

temporary.from-view="filteredAndSortedItems"

means whenever value of temporary property, of the div element, changes, assign it to filteredAndSortedItems property of the custom element view model associated with the view containing the div element.


The second binding:


temporary.bind="items | filter :key | sort :direction "

means whenever value of either items, key, direction properties changes, re-evaluate the binding and assign it to temporary prop on the div element.


Combine together two bindings, we get the following meaning of the above element snippet:

Whenever either items, key or direction properties on the custom element view model changes, recompute the final list and assign it to property named filteredAndSortedItems on the same custom element view model.

The order of bindings is left out for some fun guess. We declare from-view binding first so when temporary.bind binding gets the first value, it will trigger the assignment and assign it to the view model.


The above will not work if you mutate the items collection instead of assigning a new collection instance. example: push a new item to items, pop, shift, splice etc…

There is a work around for this situation. We can tell Aurelia to also observe the collection to reevaluate the bindings, by telling it to observe the length property:

<div
  temporary.from-view="filteredAndSortedItems"
  temporary.bind="items | filter :key | sort :direction :items.length "></div>

Now mutating the items will recompute filteredAndSortedItems


The <let/> element you see above is the better way for declaring computed expression in declarative form. It’s waiting for review. You can play with it at (this gist). But you can achieve the same result today via the first pattern.