EmberJS - 物件模型動態更新



計算屬性檢測屬性中的變化,並在使用 set() 方法呼叫時動態更新計算屬性。

語法

ClassName.set('VariableName', 'UpdatedValue');

示例

以下示例顯示屬性變化時如何動態更新值-

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');
      }),
   });

   //initializing the Person details
   var person_details = Person.create ({
      //Dynamically Updating the properties
      firstName: 'Jhon',
      lastName: 'Smith',
      age: 26,
      mobno: '1234512345'
   });

   //updating the value for 'firstName' using set() method
   person_details.set('firstName', 'Steve');
   document.write("<h2>Details of the Person: <br></h2>");
   document.write(person_details.get('Details2'));
}

現在開啟 app.js 檔案並在檔案頂部新增以下程式碼-

import dynamicupdating from './dynamicupdating';

其中,dynamicupdating 是指定為“dynamicupdating.js”的檔名,並已創建於“app”資料夾下。

接下來在匯出前,在底部呼叫繼承的“dynamicupdating”。它執行在 dynamicupdating.js 檔案中建立的 dynamicupdating 函式-

dynamicupdating();

輸出

執行 ember 伺服器,你將收到以下輸出-

Ember.js Dynamic Updating
emberjs_object_model.htm
廣告
© . All rights reserved.