Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia binding: property-getter called repeatedly

I'm currently learning and using Aurelia and something kind of weird (maybe normal) is happening.

When using the following code

export class NavBar {
  get username() {
    console.log('o_o')
    return 'name' + Date.now()
  }
}

And in the template ${username}, the username is always updating, several times per seconds (and console.log are logged several times as well of course).

The workaround is to simply use a function and not a getter and call ${username()} in the template. But is this behaviour normal? So should I use sometimes getter sometimes not?

Thanks!

like image 623
Cohars Avatar asked Dec 08 '15 19:12

Cohars


Video Answer


1 Answers

This is normal, Aurelia polls your property for changes because it has no way of knowing when your property-getter will return a different value.

If it were a simple property (without a getter), Aurelia could observe the property directly, no polling would be needed.

To avoid the polling you could tell Aurelia's binding system what to observe:

import {computedFrom} from 'aurelia-framework';

export class Foo {
  _username = 'hello';

  @computedFrom('_username')
  get username() {
    return this._username;
  }
}

Another option would be to use a one-time binding:

${username & oneTime}
like image 164
Jeremy Danyow Avatar answered Oct 30 '22 14:10

Jeremy Danyow