EmberJS 使用@each計算屬性和聚合數(shù)據(jù)

2018-01-03 14:54 更新

使用@each計算屬性和聚合數(shù)據(jù)

computed屬性訪問數(shù)組中的所有項目以確定其值。它使得簡單的添加項目和從數(shù)組中刪除項目。依賴鍵包含特殊鍵 @each ,不要使用嵌套形式的@each。這將更新當前計算屬性的binding和observer。

App.TodosController = Ember.Controller.extend({
   todos:[
      Ember.Object.create({ isDone: true }),
      Ember.Object.create({ isDone: false }),
      Ember.Object.create({ isDone: true })
   ],
   remaining: function() {
      var todos = this.get('todos');
      return todos.filterBy('isDone', false).get('length');
   }.property('todos.@each.isDone')
});

在上面的代碼中, todos.@each.isDone 依賴項鍵包含一個特殊鍵@each。當您從Todo中添加和刪除內(nèi)容時,此鍵激活觀察器。它將在剩余的計算屬性中更新。

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Computed Properties and Aggregate Data with @Each</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();

         //Extending the Ember.Controller
         App.TodosController = Ember.Controller.extend({
            //todos is an array which holds the boolean values.
            todos: [
               Ember.Object.create({ isDone: true }),
               Ember.Object.create({ isDone: false }),
               Ember.Object.create({ isDone: true })
            ],

            //dispaly the remainig values of todos
            remaining: function() {
               var todos = this.get('todos');
               //returnt the todos array.
               return todos.filterBy('isDone', false).get('length');
            }.property('todos.@each.isDone')
         });
         var car_obj = App.TodosController.create();
         document.write("The remaining number of cars in todo list: "+car_obj.get('remaining'));
     </script>
   </body>
</html>

輸出

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

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

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

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號