2016-11-18 72 views

回答

2

目前,沒有公開的API來強制添加觀察者(但存在私有的),並且根本沒有API來刪除它們。

私有函數_addComplexObserverEffect(...)在一個或多個屬性上創建觀察者。它是處理Polymer對象observers數組中每個觀察者表達式的函數。注意使用私有函數的警告是它可能在下一個版本中不可用。

你可以使用這樣的:

Polymer({ 
    ..., 

    properties: { 
    foo: String 
    }, 

    attached: function() { 
    this._addComplexObserverEffect('_fooChanged(foo)'); 
    }, 

    _fooChanged: function(foo) { ... } 
}); 

codepen

+0

有沒有計劃能夠在未來做到這一點?公開設置和未設置的方法? –

2

如果你不想使用的私有方法和它只是時間問題,而不是一個需要有ñ動態觀察者,只要元素已連接就設置一個道具,將該道具添加到觀察者,並且僅在連接時執行。

Polymer({ 
    is: 'my-el', 
    properties: { 
     bar: String, 
     attached: { 
     type: Boolean, 
     value: false 
     } 
    }, 
    observers: [ 
     '_barChagned(bar, attached)' 
    ], 
    _barChagned: function(bar, att) { 
     if(!att) return; 
     // Do your stuff 
    }, 
    attached: function() { 
     this.set('attached', true); 
    } 
    });