For example, if I wanted to hook a click event on a dynamically-created image, the code would look like this:
I know this is a bit "old-skool" but it still works well for creating dynamic content on a page when fired from, usually, the load event. A good example of this is when I need to build crazy tree controls when the nodes can be dragged around the screen (which has been happening a lot, lately).
However, from the load event onward, now-a-days I do everything client side, leveraging AJAX and JSON Web Services wherever possible. The problem I want to address today is what happens when I need to unhook and rehook these events?
Continuing with the tree example: I am currently working on an application that allows users to drag tree nodes into a div, which kicks off an AJAX animation and adds a row to a table. Once they drag a node over, it becomes "disabled" in the tree so that they can't drag it again. In order to implement this, I needed to unhook the client-side event handlers. Further, in the case where they remove the aforementioned row from the aforementioned table, the node lights up again.
So to avoid this, I really wanted to use the AJAX framework's nice $removeHandler call, which looks like this:
So to start, we have no choice but to "clear" the event in the first place, as shown above with setAttribute.
Let's keep going. The next step is to "rehook" the event when necessary. Here's where setAttribute fails for sure. Calling something like:
That's it! With this technique, you can implement client-side events using which ever method (ASP.NET on the server or AJAX on the client) suite your requirements best. But it's always coolest when the two can be intermixed to work together!