Search code examples
polymerpolymer-1.0observers

How do I set and unset an observer in Polymer?


I'm trying to understand the right way to go about setting and unsetting an observer within a Polymer component within attached() and detached() events, so it only starts watching after the element is attached. Any ideas?


Solution

  • Currently, there is no public API to imperatively add observers (but a private one exists), and no API at all to remove them.

    The private function, _addComplexObserverEffect(...), creates an observer on one or more properties. It's this function that processes each observer expression in the Polymer object's observers array. Note the caveat of using a private function is it could be unusable in the next release.

    You could use it like this:

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

    codepen