简体   繁体   English

Ember.js:如何防止多次击中该属性观察器?

[英]Ember.js: How do I prevent this property observer from being hit more than once?

In my controller I have a property and a function observing that property. 在我的控制器中,我有一个属性和一个观察该属性的函数。 When the property changes once, the observer is being hit three times - twice with the old data and once with the new data. 当属性更改一次时,观察者将被击中3次-用旧数据两次,用新数据一次。 You can see it happen in the console window of the jsbin I just created: 您可以在刚刚创建的jsbin的控制台窗口中看到它的发生:

jsbin jsbin

Usage: click one of the books (not the first one), and look in the console window at the results. 用法:单击其中一本书(不是第一本书),然后在控制台窗口中查看结果。

In my actual app, the work to be performed requires an asynchronous download. 在我的实际应用中,要执行的工作需要异步下载。 This observer is downloading the wrong content twice and the correct content once because of the three hits. 由于三击,该观察者两次下载了错误的内容,一次下载了正确的内容。 Making this problem more obvious is that the asynchronous responses do not come back in sequence. 使这个问题更加明显的是异步响应不会按顺序返回。 :) :)

An interim solution has been to schedule the download code to run later. 临时解决方案是安排下载代码在以后运行。

I'm not sure why this is happening, but the guides give a way to fix it. 我不确定为什么会这样,但是指南提供了一种解决方法。 They suggest something like this: 他们建议如下:

bookObserver: function() {
    Ember.run.once(this, 'bookWasChanged');
}.observes('book'),

bookWasChanged: function() {
    // This will only run once per run loop
}

Personally, I always make the assumption that observers could fire even when I don't want them to. 就我个人而言,我总是假设观察者即使在我不希望他们射击的情况下也可以解雇。 For instance, with this code, I would do the following: 例如,使用此代码,我将执行以下操作:

bookObserver: function() {
    var book = this.get('book');
    var lastBook = this.get('lastBook');

    if (book !== lastBook) {
        this.set('lastBook', book);
        doSomethingWithBook(book);
    }
}.observes('book')

This way, even if Ember calls your observer 1000 times, you're only going to do the work you want when the book actually changes. 这样,即使Ember打电话给您的观察员1000次,您也只会在书实际更改时去做您想要的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM