Search code examples
aurelia

How to refresh filtered aurelia repeat.for binding


Given a class with a list of items that is bound to multiple lists in the view, what is the recommended way to refresh the view when an element is modified?

Do I remove the old item and add the new item, raise an event, or something else?

export class Model {
  items: Item[];
  filter1 = x => x.isActive;
  filter2 = x => x.Value > 5;

  modifyItem(item) {
    item.isActive = true;
    item.Value = 22;
  }
}


<template repeat.for="item of items | filter:filter1">...</template>
<template repeat.for="item of items | filter:filter2">...</template>

Solution

  • You could use a signal binding behavior to notify it that something has changed and the filter needs to be refreshed:

    <template repeat.for="item of items | filter:filter1 & signal:'item-modified'">...</template>
    

    And in your component:

    import {BindingSignaler} from 'aurelia-templating-resources';
    import {autoinject} from 'aurelia-framework';
    
    @autoinject()
    export class Model {
      items: Item[];
      filter1 = x => x.isActive;
      filter2 = x => x.Value > 5;
    
      constructor(private signaler: BindingSignaler) { }
    
      modifyItem(item) {
        item.isActive = true;
        item.Value = 22;
        signaler.signal('item-modified');
      }
    }