Using change watchers to observe native properties under Object.observe()
Asked Answered
H

2

7

Now that Object.observe() is on by default in Chrome, I'm running into a bunch of cases where I want to reuse the browser's built in property (hidden, title, draggable), but *Changed watchers no longer get called when the property changes.

One example is hidden: http://jsbin.com/jizikaje/1/edit (hiddenChanged() is never called)

My current workaround is to use attributeChanged() to observe the attribute changing:

attributeChanged: function(attrName, oldVal, newVal) {
  // Cannot use *Changed watchers for these native properties.
  if (attrName == 'hidden') {
    this.marker.setVisible(!this.hidden);
  }
}

What is the recommended approach?


BTW, throwing a warning when trying to use native properties will go a long for debugging: https://github.com/Polymer/polymer/issues/379

Hainaut answered 12/4, 2014 at 20:53 Comment(6)
The alert() seems to be happening for me in Chrome 34. Maybe this has been fixed?Votyak
Chrome 34 does not have Object.observe(). It uses dirty checking.Hainaut
Ah yeah, this makes sense. The DOM hasn't been moved into V8 yet, so Object.observe() probably doesn't work on DOM elements.Votyak
So you want to listen for a DOM element state change? Use the mutationobserver as mentioned in the answer: jsfiddle.net/LkxWXExhilarant
You could certainly use a MO to detect attribute changes on the element, but you already get the attributeChangedCallback for free :) Either way, the solution is hacky. It relies on the fact that the native IDL properties also expose an attribute of the same name. So you're not observing the property, but attribute changing.Hainaut
Things have changed for Polymer and ECMA script since this question was posted and subsequently the question is of little value now.Cogitate
V
0

Object.observe() is for JavaScript stuff, and MutationObserver is for DOM elements. MutationObserver would probably work better in this case.

Votyak answered 8/6, 2014 at 0:27 Comment(1)
Note, to save trouble in the future: MutationObservers are only fired for actual DOM-tree mutations (i.e., those that effect the structure and attributes of the DOM). This will not allow you to catch changes to native properties. As of Oct 2014, there's no way to do this in Chrome -- you should be able to shim native property getters via Object.defineProperty(), but that won't work because Object.getOwnPropertyDescriptor() is broken for native properties on Chrome and Safari.Ardyce
C
0

It looks like this is an old post for Polymer 1 and probably is no longer a useful question.

The Object.observe() proposal has been withdrawn and is not supported by any browsers.

Polymer now uses declared properties which supports observers.

Cogitate answered 27/12, 2016 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.