Aurelia使用ES5计算属性

Aurelia computed properties with ES5

本文关键字:属性 计算 ES5 使用 Aurelia      更新时间:2023-09-26

我正在通过Aurelia教程工作,但故意只使用ES5和AMD/RequireJS,因为最初我试图减少技术过载,我可能需要在我当前的生产应用程序中引入(目前使用Angular,但我正在考虑切换到Aurelia而不是Angular 2),但我坚持获得计算属性工作。

我注意到四月的更新从对象原型中删除了允许以下语法的计算函数,但我不确定我应该做什么而不是以下语法:

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

我可以用下面的代码实现同样的效果,但是考虑到要实现的效果,它似乎相当啰嗦!有正确的奥蕾莉亚方式吗?

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

你所做的是正确的-你总是可以重新添加计算工厂方法,因为编写所有这些额外的ES5代码可能会变得乏味。

我还建议指定computed属性的依赖项以优化数据绑定效率。下面的代码片段是等价的:

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