简体   繁体   中英

Observing changes to DOM properties

I would like to know when certain properties of an arbitrary object change.

I read the answer to this question: " extend setter default object " which seemed to suggest the solution using getters and setters. However, I tried to use it to trap changes to both the id and style properties of a DOM object and it did not work. One strange thing I observed is that as soon as I create a setter for the id field is the original id field vanishes, so attempts to read or write the value fails. As the property may be a DOM property, which sometimes aren't simple variables, I can't simply create my own variable as I can't arbitrarily re-create whatever underlying functionality is generating the value.

All I really want to do is detect when the property changes, and pass the change through transparently.

Some further research led me to this page presenting a polyfill for Object.watch . However, while this watch function appears to let me see when the properties of an object change, the actual properties wind up not being changed at all.

You can use mutation observers to watch for changes in attributes. This works well for DOM properties that get/set markup attributes. Compared to mutation events, mutation observers run long after the actual mutation, instead of immediately. I've read that mutation observers perform better than mutation events.

You also bring up the question of how to access the original getter/setter when you redefine a property. You won't need to worry about this if you use the mutation observer solution. In some browsers, such as Firefox, the original functionality of a property like id is also implemented as a getter/setter. For example, if you ran Object.getOwnPropertyDescriptor(Element.prototype, 'id').set.call(myElement, 'asdf') , it would be like myElement.id = 'asdf' , even if myElement.id were redefined. Some browsers don't do it this way. Chromium, for example, is still working on implementing this aspect of Web IDL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM