Polymer. Way to dynamically add or remove observer

对着背影说爱祢 提交于 2019-12-08 16:47:26

问题


Is there a way to add or remove observer not in the moment of element initing? I can define observer this way:

observers: ['dataChanged(data.*)']

Can i remove this observer later or can I set this observer different way than that?


回答1:


You can easily add an observer dynamically, either by:

this._addObserverEffect("property", observerFunction);

or

this._addComplexObserverEffect("dataChanged(data.*)");

Removing is harder and Polymer does not provide a function to do this. Although you could search for it in the _propertyEffects array, I wouldn't recommend it. Maybe just check in your observer function whether it should still be active, and return if not.




回答2:


you maybe can try this way: configure your data property in the element with notify: true, so you can add a listener to changes with plain js

var element=document.querySelector("#YOUR-ELE-ID");
element.addEventListener("data-changed", function(e) {
 //triggered when data property changes
});

https://www.polymer-project.org/1.0/docs/devguide/properties#notify

and to remove the bound listener you can call removeEventListener

https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener

Example 1 - plain JS :

document.addEventListener('WebComponentsReady', function(e) {
    var element=document.querySelector("#YOUR-ELE-ID");
    element.addEventListener("data-changed", function(e) {
     //triggered when data property changes
    });
});

Example 2 - in custom element:

//...element definition...
ready: function() {
    var element=document.querySelector("#YOUR-ELE-ID");
    element.addEventListener("data-changed", function(e) {
     //triggered when data property changes
    });
}


来源:https://stackoverflow.com/questions/39648192/polymer-way-to-dynamically-add-or-remove-observer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!