EmberJS 使用@each计算属性和聚合数据
使用@each计算属性和聚合数据
computed属性访问数组中的所有项目以确定其值。它使得简单的添加项目和从数组中删除项目。依赖键包含特殊键 @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中添加和删除内容时,此键激活观察器。它将在剩余的计算属性中更新。
例子
<!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>
输出
让我们执行以下步骤,看看上面的代码如何工作:
将上述代码保存在 computed_prop_agg_each.html 文件中
在浏览器中打开此HTML文件。