简体   繁体   中英

Aurelia computed properties with ES5

I'm working through an Aurelia tutorial but intentionally only using ES5 and AMD/RequireJS since initially I'm trying to reduce the technical overload which I may need to introduce in my current production app (which is currently using Angular but I'm thinking of swapping to Aurelia instead of Angular 2) but I'm stuck with getting computed properties working.

I've noticed that an update made in April removed the computed function from the Object prototype which allowed the following syntax but I'm not sure what I should do instead of the following syntax:

Welcome.computed({
    fullName : function() { return this.firstName + " " + this.lastName; }
});

I can achieve the same effect with the following but it seems quite verbose given what's being achieved! Is there a correct Aurelia way?

Object.defineProperty(
  Welcome.prototype,
  "fullName",
  {
    get: function() { return this.firstName + " " + this.lastName },
    enumerable: true
  });

What you're doing is correct- you could always re-add the computed factory method since writing all this extra ES5 code could get tedious.

I'd also recommend specifying the computed property's dependencies to optimize data-binding efficiency. This following code snippets are equivalent:

ES5:

function fullName() { return this.firstName + ' ' + this.lastName }
fullName.dependencies = ['firstName', 'lastName'];
Object.defineProperty(
  Welcome.prototype,
  'fullName',
  {
    get: fullName,
    enumerable: true
  });

ES6/ES7:

@computedFrom('firstName', 'lastName')
get fullName() {
  return `${this.firstName} ${this.lastName}`;
}

http://aurelia.io/docs.html#adaptive-binding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM