EmberJS - 單向繫結



物件模型繫結透過使用單向 binding 方法 computed.oneWay() 指定一個方向的更改,並且在透過覆蓋指定另一個屬性上的行為時非常有用。

示例

下列示例透過覆蓋指定另一個屬性上的行為 −

import Ember from 'ember';

export default function() {
   var CarOne = Ember.Object.create ({
      
      //primary value
      TotalPrice: 860600
   });

   var Car = Ember.Object.extend ({
      TotalPrice: Ember.computed.oneWay('CarOne.TotalPrice')
   });

   var Car = Car.create ({
      CarOne: CarOne
   });
   
   //Changing the user object name, changes the value on the view
   CarOne.set('TotalPrice', 860600);

   //Car.TotalPrice will become "860600"
   Car.set('TotalPrice', 930000);  // changes to the view don't make it back to the object.
   document.write('<h3>One Way Binding<h3>');
   document.write('Value of car : ' + CarOne.get('TotalPrice')); //display value as 860600
}

現在開啟 app.js 檔案並在檔案的開頭新增以下行 −

import objectmodelonewaybinding from './objectmodelonewaybinding';

其中,objectmodelonewaybinding 是指定為 "objectmodelonewaybinding.js" 並創建於 "app" 資料夾下的檔名。

接下來在匯出之前,在底部呼叫繼承的 "objectmodelonewaybinding"。它執行在 objectmodelonewaybinding.js 檔案中建立的 objectmodelonewaybinding 函式 −

objectmodelonewaybinding();

輸出

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

Ember.js Object Model One Way Binding
emberjs_object_model.htm
廣告
© . All rights reserved.