Reputation: 369
I'd like to understand how the CustomEvent
system works, in Javascript.
[EDIT2]
The dream solution is here : http://www.html5rocks.com/en/tutorials/es7/observe/
[/EDIT2]
[EDIT]
This piece of codes illustrates pretty well the type of DOM
-aware system I'm looking for, thx to @Jared Farrish, There is also the deferred method. But I'm still thinking it is a kind of javascript limitation and that the langage deserves to implement a clever way to do. Ideally, children would not have to execute orders given by parent or by any other element. Instead, a child node should takes its own decisions, by knowing in real-time the interesting parts of DOM activity.
var body = document.body,
btn = document.getElementById('fire'),
warn;
warn = document.createEvent('CustomEvent');
warn.initEvent('warning', true, true);
body.addEventListener('warning', function() {
body.style.backgroundColor = 'blue';
});
btn.addEventListener('warning', function() {
this.style.backgroundColor = 'green';
});
btn.addEventListener('click', function init() {
body.dispatchEvent(warn);
btn.dispatchEvent(warn);
});
source : http://jsfiddle.net/p6myjLza/2/
[/EDIT]
Saying I create this very basic event :
var warning = new CustomEvent('warning', {
'detail': 'This is a warning!'
});
Now the object warning
contains useful data. It is stored in the browser memory. Let's trigger it.
document.dispatchEvent(warning);
By doing above statement, I think I say to document
: "hey dude, fire this specific event plz". And then, the event is triggered. And how far as I understand, I assume it also means that (somehow) the DOM
is aware that the event has been triggered.
Now I would like another element, saying body, to change is style.backgroundColor
from transparent to red each time the event warning
is triggered. In other word, I want body to listen to this specific event and react consequently.
document.getElementsByTagName('body')[0].addEventListener('warning',
function(e){
this.style.backgroundColor = 'red';
}, false);
But this works not.
Actually, it works if I switch the position of dispatchEvent()
and addEventListener()
by initializing the second before the first. But it is not what I am expecting from Javascript. What I want to achieve is the ability to trigger an event somewhere, and ordering some element elsewhere to catch it and react each time this event is triggered.
Is it something achievable?
Note : I discovered promises today and thought they were what I'm looking for, but they're not as they just capable to "chain" things without being able to delay them.
Upvotes: 2
Views: 3195
Reputation: 29009
You've almost got it! What happens, however, is that you are triggering the event on the document
level and the body
tag, where the event handler is, is lower - events bubble up when triggered.
If you simply dispatch the event from the body
, you'd see it triggers the handler
document.getElementsByTagName('body')[0].dispatchEvent(warning);
Upvotes: 2