How to refresh listeners in Prototype
Lets say, you are making a site, were everything is AJAX, and you rely on event handlers to know when people double click on this element, drag the image across the site, etc. Normally you would start listening to things once the DOM fires (when the page loads), but problem is, it only fires once. Here is an example of a normal “onload” listener in Prototype.js:
Event.observe(window, 'load', function () {
$$('tr[rel="file"]').each(function(element) {
element.observe('click', function(event) {
new Ajax.Request('file_info.php', {
asynchronous: true,
method: 'get',
parameters: 'ajax=true',
onComplete: function(t) {
$('files').update(t.responseText);
}
});
event.stop();
});
});
});
So, once the window loads, tell every table row with the rel attribute named “file” to some things once its clicked (in this case, gets the file info). Problem is, with all the new table rows coming in, Prototype wasn’t told to listen to the new table rows, only the previous ones that are gone.
I spent about an hour trying to figure out how to re-load the observe above. With tension building, I finally found something in the Prototype API documentation. You can establish your own psuedo type observation, which you would call when the window loads! Here is an example:
document.observe('start:files', function() {
$$('tr[rel="file"]').each(function(element) {
element.observe('click', function(event) {
new Ajax.Request('file_info.php', {
asynchronous: true,
method: 'get',
parameters: 'ajax=true',
onComplete: function(t) {
$('files').update(t.responseText);
document.fire('start:files');
}
});
event.stop();
});
});
});
Event.observe(window, 'load', function (event) {
document.fire('start:files');
});
So when the window loads, it will load another observer. Although this seems redundant, it’s the only way to re-fire the listener when you need to. Let me note, that the start:files you can name it anything you want really, although it should have a : somewhere in-between it.
