EmberJS - 对象模型链式计算属性

链式计算属性用于将一个或多个预定义计算属性聚合到单个属性下。

语法

var ClassName = Ember.Object.extend ({
   NameOfComputedProperty1: Ember.computed(function() {
      return VariableName;
   }),

   NameOfComputedProperty2: Ember.computed(function() {
      return VariableName;
   });
});

示例

以下示例展示了如何使用计算属性作为值来创建新的计算属性 −

import Ember from 'ember';

export default function() {
   var Person = Ember.Object.extend ({
      firstName: null,
      lastName: null,
      age: null,
      mobno: null,
      
      //定义 Details1 和 Details2 计算属性函数
      Details1: Ember.computed('firstName', 'lastName', function() {
         return this.get('firstName') + ' ' + this.get('lastName');
      }),

      Details2: Ember.computed('age', 'mobno', function() {
         return 'Name: ' + this.get('Details1') + '<br>' + ' Age: ' + this.get('age') + 
            '<br>' + ' Mob No: ' + this.get('mobno');
      }),
   });

   var person_details = Person.create ({
      //初始化变量的值
      firstName: 'Jhon',
      lastName: 'Smith',
      age: 26,
      mobno: '1234512345'
   });
   
   document.write("<h2>Details of the Person: <br></h2>");
   //通过 get() 方法显示值
   document.write(person_details.get('Details2'));
}

现在打开 app.js 文件并在文件顶部添加以下行 −

import chainingcomputedproperties from './chainingcomputedproperties';

其中,chainingcomputedproperties 是指定为"chainingcomputedproperties.js"并在"app"文件夹下创建的文件的名称。

现在,在导出之前,在底部调用继承的"chainingcomputedproperties"。它执行在 chainingcomputedproperties.js 文件中创建的 chainingcomputedproperties 函数 −

chainingcomputedproperties();

输出

运行 ember 服务器,您将收到以下输出 −

Ember.js Chaining Computed Properties

emberjs_object_model.html