1

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.

Community
  • 1
  • 1
Michael
  • 9,060
  • 14
  • 61
  • 123
  • Try mutaton events https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events although not cross browser. – sabithpocker Jun 27 '14 at 19:58
  • @sabithpocker only works on attribute changes, not property changes – Michael Jun 27 '14 at 20:01
  • Can you provide an example scenario of what you are trying to do? – sabithpocker Jun 27 '14 at 20:03
  • @sabithpocker I want to be one change on the page to trigger another change, when the function creating the second change has no knowledge of what might make the original change. – Michael Jun 27 '14 at 20:10
  • I would suggest you to update the question with a minimal example. I am confused if you are looking for some data binding or observer patterns or just watching DOM element's mutation. Hope someone helps, ill be leaving my desk now. – sabithpocker Jun 27 '14 at 20:16

1 Answers1

0

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.

guest
  • 6,450
  • 30
  • 44