2.5 The Object Model -- Observers

Ember支持监视任何属性,包括计算的属性。你可以使用Ember.observer为一个对象设置一个监视者:

Person = Ember.Object.extend({
    //these will be supplied by 'create'
    firstName: null,
    lastName: null,
    
    fullName: Ember.computed('firstName', 'lastName', function () {
          var firstName = this.get('firstName');
          var lastName = this.get('lastName');
          
          return firstName + ' ' + lastName;
    });

    fullNameChanged: Ember.Observer('fullName', function () {
          //deal with the change
    });
});

var person = Person.create({
    firstName: 'Yehuda',
    lastName: 'Katz'
});

person.set('firstName', 'Brohuda'); // observer will fire
  • 因为计算的属性fullName依赖于firstName,更新firstName也会启动fullName的监视者。

一、Observers and Asynchrony(监视者和异步)

1. Ember中的监视者目前是同步的。这意味着一旦监视到其中一个属性改变它们就会启动。它很容易解释属性还未同步的bugs。

Person.reopen({
    lastNameChanged: Ember.observer('lastName', function () {
        //监视者依赖lastName和fullName。因为监视者是同步的,
       //当方法被调用时,fullName的值还没有被更新,所以会输出它之前的值
       console.log(this.get('fullName'));
    });
});

2. 当监视多个属性的时候,这种同步的行为也可以导致监视者被启动多次。

Person.reopen({
    partOfNameChanged: Ember.observer('firstName, 'lastName', function () {
        //因为firstNam和lastName都被设置了,这个监视者将会被启动两次。
    });
});

person.set('firstName', 'John');
person.set('lastName', 'Smith');

3. 为了克服这些问题,你应该使用Ember.run.once。一旦所有绑定是同步的,这将确保任何处理你的需求仅会发生一次并发生在下一个循环: 

Person.reopen({
  partOfNameChanged: Ember.observer('firstName', 'lastName', function() {
    Ember.run.once(this, 'processFullName');
  }),

  processFullName: Ember.observer('fullName', function() {
    // This will only fire once if you set two properties at the same time, and
    // will also happen in the next run loop once all properties are synchronized
    console.log(this.get('fullName'));
  })
});

person.set('firstName', 'John');
person.set('lastName', 'Smith');

二、Observers and Object Initialization

1. 监视者不会启动直到对象初始化完成以后。

如果你需要监视者启动作为初始化程序的一部分,你不能依靠set的作用。相反,通过使用Ember.on()指定监视者应该在init之后运行。

Person = Ember.Object.extend({
    init: function() {
        this.set('salutation', 'Mr/Ms');
    },
    
    salutationDidChange: Ember.on('init', Ember.observer('salutation', function(){
        //some side effect of salutation changing
    }));
});    

三、剩余的计算属性不触发监视者

1. 如果你从来没有get一个计算属性,尽管它依赖的keys变化了,它的监视者也不会启动。你可以理解为值从一个位置的值变为了另一个。

2. 这通常不会影响应用程序代码,因为当它们被获取的时候计算属性几乎总是在同一时间被监视。例如,你获得了计算属性的值,把它放到DOM中,然后监视它,这样一旦属性变化你就会更新DOM。

3. 如果你需要监视计算属性但是目前没有检索它,仅仅是在你的init方法中获取它。

四、Outside of Class Definitions(在类定义的外面)

你也可以使用addObserver在类定义的外面为一个对象添加监视着。

person.addObserver('fullName', function(){
    //deal with the change
});
posted @ 2016-01-21 11:01  鱼不吐泡泡  阅读(406)  评论(0编辑  收藏  举报