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,
      
      //Defining the Details1 and Details2 computed property function
      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 ({
      //initializing the values for variables
      firstName: 'Jhon',
      lastName: 'Smith',
      age: 26,
      mobno: '1234512345'
   });
   
   document.write("<h2>Details of the Person: <br></h2>");
   //displaying the values by get() method
   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.htm
廣告
© . All rights reserved.