computed屬性訪(fǎng)問(wèn)數(shù)組中的所有項(xiàng)目以確定其值。它使得簡(jiǎn)單的添加項(xiàng)目和從數(shù)組中刪除項(xiàng)目。依賴(lài)鍵包含特殊鍵 @each ,不要使用嵌套形式的@each。這將更新當(dāng)前計(jì)算屬性的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 依賴(lài)項(xiàng)鍵包含一個(gè)特殊鍵@each。當(dāng)您從Todo中添加和刪除內(nèi)容時(shí),此鍵激活觀(guān)察器。它將在剩余的計(jì)算屬性中更新。
<!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 文件中
在瀏覽器中打開(kāi)此HTML文件。
更多建議: