Set getter dependencies without using @computedFrom

Just found out how to do this, sharing to the community. Let me know if my approach has problem/limitation.

The use case is, I like to keep my app repo lean, so I have habit to push down as many business logic as I could to seperate repos. My app repo adds them using git repo tag.

Those packages are pure logic, have no dependencies on Aurelia. I can reuse the code in other projects (some are not web apps).

The problem is, when you use getter property xmax in Aurelia html template, it ends up as a dirty check.

class Box {
  // x, y, width, hight
  get xmax() {
    return this.x + this.width;
  }
}

One possible solution is add aurelia-binding to your lib’s dependencies, and use @computedFrom('x', 'width') on xmax.

But that defeats our will to keep that lib out of Aurelia.

Here is how you can manually teach Aurelia the dependencies of xmax, without using computedFrom.

class Box {
  // x, y, width, hight
  get xmax() {
    return this.x + this.width;
  }
}
// this got same effect as @computedFrom('x', 'width')
Object.getOwnPropertyDescriptor(
  Box.prototype, 'xmax'
).get.dependencies = ['x', 'width'];
2 Likes

Pretty neat! Thanks for sharing :slight_smile:

You could always use aurelia-computed which seems to do a great job.

1 Like

Just read through aurelia-computed source code. Instead of using a full-featured AST parser, it uses aurelia-binding’s internal parser to parse the getter function body.

aurelia-binding’s internal parser was designed to parse the expressions in html template bindings, it only understands a limited subset of JavaScript expression syntax. For example, it doesn’t understand if-else statement, it also does not accept multi statements.

The limitation of aurelia-computed is that it only can understand simple one-line getter implementation like the get xmax() in my code. Anything more complex than that, it gives up silently, aurelia will still use dirty-check on those failed.

Copied from its readme:

One-liners that don’t access anything outside the scope of the view-model are good candidates for observation by this plugin