I am trying to monitor changes to select box (or nested option
elements) with new Mutation Observer functionality. However, only "setAttribute" is triggering mutation observer's callback for me.
Here's the code I am using:
~function(doc, $) {
var select = $('select');
// http://www.w3.org/TR/dom/#mutation-observers
var observer = new WebKitMutationObserver(function(mutations) {
alert(mutations.length + " mutations happened");
});
observer.observe(select, {
// monitor descendant elements – changing `selected` attr on options
subtree: true,
attributes: true
});
// this triggers Observer's reaction, but doesn't update select box UI
select.setAttribute('value', 'whee');
// this updates select box UI, but doesn't trigger mutation observer's callback
select.value = "whee";
// this also updates the UI, but doesn't trigger mutation observer's callback
select.getElementsByTagName('option')[0].selected = true;
//
// neither does manual selecting of options trigger mutation observer unfortunately :(
button.addEventListener('click', function(e) {
e.preventDefault();
// my goal is to react to this change here
select.value = Math.random() > .5 ? "whee" : "whoa";
}, false);
}(document, function(selector) { return document.querySelector(selector); });
And here's this code in action http://jsfiddle.net/gryzzly/wqHn5/
I would like to react to changes to attributes (selected
on <option>
or value
on <select>
), any suggestion on why observer doesn't react is more than welcome!
I am testing this in Chrome 18.0.1025.168 on Mac OS X. Production code would of course also have a moz
prefix for the constructor and unprefixed version too, this is testing code.
UPD.
Tested the code in Firefox Nightly too and it behaves the same way as in Chrome, as well as in Chrome Canary. I have filled the bug for both browsers:
Please comment and vote for these bugs if you also find this problem annoying.
@gryzzly, I've updated the Chromium bug with a detailed response: http://code.google.com/p/chromium/issues/detail?id=128991#c4
Mutation Observers are limited to observing the DOM serialized state. If you'd like to know if Mutation Observers can observe something, just do take a look at what innerHTML outputs for the element. If you can see the change in state reflected in changes to the markup which that produces, then Mutation Observers should be able to hear about it.
TL;DR: this is working as intended; to observe changes to IDL attributes like HTMLSelectElement.value, input events like onclick or onchange are probably your best bet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With