EmberJS 計算屬性

2018-01-03 17:10 更新

計算屬性

計算屬性允許將函數(shù)聲明為屬性。Ember.js在需要時自動調(diào)用計算的屬性,并在一個變量中組合一個或多個屬性。

App.Car = Ember.Object.extend({
   CarName: null,
   CarModel: null,

   fullDetails: function() {
      return this.get('CarName') + ' ' + this.get('CarModel');
   }.property('CarName', 'CarModel')
});

在上述代碼中, fullDetails 是調(diào)用 property()方法來呈現(xiàn)兩個值(即CarName和CarModel)的計算屬性。每當 fullDetails 被調(diào)用時,它返回 CarName CarModel

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Computed Properties</title>
      <!-- CDN's-->
      <script src="/attachements/w3c/handlebars.min.js"></script>
      <script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
      <script src="/attachements/w3c/ember.min.js"></script>
      <script src="/attachements/w3c/ember-template-compiler.js"></script>
      <script src="/attachements/w3c/ember.debug.js"></script>
      <script src="/attachements/w3c/ember-data.js"></script>
   </head>
   <body>
      <script type="text/javascript">
         App = Ember.Application.create();
         App.Car = Ember.Object.extend({
           //the values for below Variables to be supplied by `create` method
           CarName: null,
           CarModel: null,
           fullDetails: function(){
              //returns values to the computed property function fullDetails
              return ' Car Name: '+this.get('CarName') + ' Car Model: ' + this.get('CarModel');
             //property() method combines the variables of the Car
           }.property('CarName', 'CarModel')
         });

         var car_obj = App.Car.create({
            //initializing the values of Car variables
            CarName: "Alto",
            CarModel: "800",
         });
         //Displaying the Car information
         document.write("Details of the car: <br>");
         document.write(car_obj.get('fullDetails'));
      </script>
   </body>
</html>

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:

  • 將上述代碼保存在 computed_prop.html 文件中。

  • 在瀏覽器中打開此HTML文件。

下表列出了計算屬性的屬性:

序號屬性及描述
1 替代調(diào)用

它將一個或多個值傳遞給計算的屬性,而不使用property()方法。
2 鏈接計算屬性

鏈接計算的屬性用于與一個或多個預(yù)定義的計算屬性進行聚合。
3 動態(tài)更新

調(diào)用計算屬性時動態(tài)更新。
4 設(shè)置計算屬性

使用 setter和getter 設(shè)置計算的屬性。
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號