Skip to content
Advertisement

How to create a JavaScript template engine that doesn’t destroy events attached to the template?

I have been evaluating a lot of different client-side JS template engines (doT, parrot, dust.js, microtemplating, underscore, etc). They all work similarly, using some type of tags to represent data, and with some giving the ability to embed pure JS into the template, including loops, if/then, etc. However, they all work by converting the template itself into a string, then into javascript, in order to interpolate the variables, execute loops, etc.

When this conversion happens, any event handlers that were attached to the original objects within the template (i.e. created by jQuery at document.ready) are of course lost. To add these handlers back to the resulting HTML would then necessitate going back and re-applying any such event handlers after each template rendering.

I’m trying to think of a way to create a template engine with full javascript support, but which preserves any events attached to the template before cloning.

Imagine a scenario where the template is for a list of items. Each item includes buttons which perform specific tasks on that item (i.e. edit, delete, rename, copy, you get the idea).

To make the code clean and easily maintainable, it would make sense to apply Click events to these buttons in the template HTML at document.ready(). Then each time the template is cloned for a new list item, the events are cloned too.

However, with current templating libraries, all events are lost at the cloning stage, which necessitates applying all events to the cloned object each time the list is updated. If this is live data, or if the user is adding new items to the list, this seems like it would become very convoluted to keep track of the events and ensure they are properly attached each time an item is added.

I know jQuery has a clone() function which clones events, and this works great for basic templates, but when you get try to incorporate arbitrary JavaScript into the template, this becomes impractical.

I am trying to avoid templates which depend on html element attributes to configure loops, decisions, etc, because the template code becomes very ugly. A clean template with simple tags for data substitutions, simple JS for-loops for repeated elements, and simple references to the source data, is desired.

Anyone have ideas on how to do this?

Advertisement

Answer

Instead of over-complicating templating, you should use event delegation, so that this problem does not even present itself.


And yes, jQuery had .delegate – it is deprecated, and has been replaced by .on, which can do the same thing, see http://api.jquery.com/delegate/#entry-longdesc

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement