Remember to reset the YUI listeners on updated content

I had event listeners set on elements added dynamically to the page not working:
my original content Click here to replace content
When you click on the test_link, the content of the div is updated with a undo_link, for which we have a click event listener to redisplay the original content. Note how the event listener for the undo_link is set before this link is present in the page. The simple solution is to set the event listener in the change_content function after the undo_link has been added to the document.

Testing onavailable

Writing this blog post, I wondered if I could use the onavailable method to set the listener once the test_link or undo_link are included in the document. Two problems seem to invalidate this approach:
  • the onavailable method is executed only the first time the element is inserted in the document. If it is removed and re-added, the method is not executed.
  • the onavailable method seems meant to accelerate javascript actions at page load time, so action can be taken immediately after the element is available. This is also shown by the fact that the polling of the element is not continuous, but only happens during a configurable time span (by default 10 seconds).
I've put a little demo page illustrating this.