有没有办法修改观察值而不触发Polymer中的观察者回调

时间:2015-09-19 14:49:47

标签: polymer object.observe

就像标题所说的那样。有没有办法在不触发Polymer的观察者回调的情况下修改观察值?

例如

Polymer({
        is: 'my-component',

        properties: {
            aValue: {
                type: Number,
                value: 0,
                observer: '_valueChanged',
                notify: true
            },
            ref: {
                type: Object,
                computed: '_computeRef(channel, channelNumber)'
            }
        },

        _computeRef: function(channel, channelNumber) {

            var ref = new Firebase("/*link*/");
            ref.on("child_changed", function(data) {
               this.aValue.setWithoutCallingObserver(data.val());
            }.bind(this));

            return ref;
        },

        _valueChanged: function() {
            var message = { aValue: this.aValue };
            if (this.ref) {
                this.ref.set(message);
            }
        }

    });

这很有用,因为现在我遇到了以下情况的延迟:

  1. 在第三方应用中调整aValue
  2. Firebase更新所有客户端
  3. .on回调设置值并触发观察者回调
  4. 导致.set到firebase
  5. 回到2。
  6. 更新:问题与firebase无关。我相信解决方案是控制如何将更新应用于Polymer中的观察值。部分原因是firebase商店中的值的更改也可以由第3方(不一定是Web)应用程序进行。

2 个答案:

答案 0 :(得分:4)

据我所知,没有内置的方法来设置属性值而不触发它的观察者。

您无法控制观察者调用的方式/时间/参数,但您可以控制过程体,幸运的是,您正在使用共享状态(this)。

因此,您可以根据可以在函数中访问的标志来修改函数的行为,但不必传入。

例如:

_valueChanged: function (new_val, old_val) {
   if (this._observerLock) { return; }

   var message = { aValue: this.aValue };
     if (this.ref) {
       this.ref.set(message);
     }
   }
 }, 
...

然后,您可以实现_setWithoutCallingObserver()方法,如:

_setWithoutCallingObserver: function (value) {
  this._observerLock = true;
  this.aValue = value;
  this._observerLock = false;
}

答案 1 :(得分:-1)

只需将_valueChangedMethod更改为此

即可
LI

这将使观察者仅在值实际改变时才能工作。

相关问题