“Declaratively” binding events when using innerHTML

Yesterday I was editing some JavaScript code that used innerHTML to insert HTML into the Document Object Model (DOM). Given it’s not the best and even fastest way to accomplish the task the code was written this way so it was what I had to work with. That is I had code like this:

// build HTML into string
var htmlResult = "
"; htmlResult += Click me!"; htmlResult += "
"; ... ... // insert HTML into DOM dojo.byId("target").innerHTML = htmlResult;

One major shortcoming of this approach is that that it is hard to hook up JavaScript events using dojo and similar frameworks as they require the target element of the event to be in the DOM at the time of the wiring. No declarative approach I know of there. To solve it I opted for a simple – although a bit kludgy approach where I simply save the event methods for later and apply once the DOM has been constructed. Easy. Like this:
var htmlResult = “

“;
dojo.byId(“target”).innerHTML = htmlResult;

// define holder for onclick functions
var onclickFunctions = {};

// build HTML into string
var htmlResult = "
"; htmlResult += Click me!"; htmlResult += "
"; ... ... // define onclick functions for ids onclickFunctions["myLink"] = function() { console.log("Do stuff..."); } ... ... // add html to DOM dojo.byId("target").innerHTML = htmlResult; // hook up event handlers dojo.forEach(Object.keys(onclickFunctions, function(id) { try { var elem = dojo.byId(id); if (elem) elem.onclick = onclickFunctions[id]; } catch (e) {} });

Kludgy I know but it gets the job done.

One thought on ““Declaratively” binding events when using innerHTML”

Comments are closed.