8

正如标题所说。有没有办法在不触发 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。

更新:这个问题与火力无关。我相信解决方案是控制如何将更新应用于 Polymer 中的观察值。部分原因是第 3 方(不一定是 Web)应用程序也可以对 firebase 存储中的值进行更改。

4

2 回答 2

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;
}
于 2016-01-03T13:35:23.057 回答
-1

只需将 _valueChangedMethod 更改为此

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

这将使观察者仅在值实际更改时才进行工作。

于 2015-09-21T23:21:20.003 回答