Reputation: 41483
So,
I'm using event bubbling to capture child DOM events... I'm attaching click events to a div
wrapper and also attaching click events to that wrapper's children... like so:
<div onclick="foo();">
<div onclick="bar();">
Hello World!
</div>
</div>
function foo() {
alert(window.event.abc.one);
};
function bar() {
window.event.abc = {one: "23"};
};
As you can see, I'm assigning a custom object to abc
. I'm using this as a way to send messages to click handlers further up the chain... and avoid using closures on every child element. In other browsers, you can assign whatever you like to the event
object... and this works very well.
However (of course), this does not work in IE. I tried using the "data" property on the event object, but this only allows strings.
Any other way I can accomplish this same functionality without using a closure on every child object?
Upvotes: 1
Views: 242
Reputation: 490183
Not pretty, but this should work. Box9 the magnificent suggested something I overlooked, and that is, if something sets a property before it bubbles to bar()
(for example, an event handler on a descendent of your inner div
), it will be overwritten.
var msg = {};
// When the event bubbles up to document, we'll reset it to an empty object
// literal, ready for new information to be attached to it.
document.onclick = function() { msg = {} };
function foo() {
alert(msg.one);
};
function bar() {
// Assign this property only, so if something else had attached a property
// to `msg`, it will remain intact.
msg.one = "23";
};
Upvotes: 2