如何让@each观察者触发一次

时间:2014-06-03 20:54:02

标签: ember.js

我有一个观察数组属性的观察者。我有一个遍历数组的动作并设置该属性,因此它被多次触发。我想知道我能不能只触发一次。例如:

    App.EmployeesController = Ember.ArrayController.extend({

      content:Ember.A([
        Ember.Object.create({'name':'a','active':true}),
        Ember.Object.create({'name':'b','active':false}),
        Ember.Object.create({'name':'c','active':false})
      ]),

      test: function(){
        console.log('inside here');//WANT THIS TO FIRE JUST ONCE
      }.observes('content.@each.active'),

      setActive: function(name){
        var self= this;
        Ember.run(function(){
           self.get('content').forEach(function (emp) {
               emp.set('active', (emp.get('name') === name));
            });  
        });

      }

    });

这是一个jsbin:http://jsbin.com/vuyezahi/3/edit

1 个答案:

答案 0 :(得分:1)

嗯,你正在改变数组中的两个值。所以在技术上它应该发射两次,但如果你想要你可以限制方法只在指定的时间内调用一次(我做了10ms)。

      test: function(){
        Em.run.throttle(this, this.test2, 10);
      }.observes('content.@each.active'),

      test2: function(){
        console.log('inside here');
      },

http://jsbin.com/vuyezahi/6/edit

相关问题