0

"Stable application development requires strict organizing of code into clear 'blocks'."

To that end I am using Mustache to render data from my scripts into my HTML.

I am storing my Mustache templates in special script tags:

<script id="template" type="text/template">
    Mustache template goes here and is invisible
</script>

To render the template in a div I simply call the Mustache render function

var template = $('#template').html();
$('#someDiv').html(Mustache.render(template));

Now imagine I want to bind a click event to an element in a Mustache template or Cache the elements that I will use later... I obviously can't do that on page load because the template is not rendered yet.

To get the event to work I have to declare an event only after I have rendered the HTML. To use an element I have to manually select it when I need it e.g. $('.foo') instead of the cached this.foo

The consequence is that now I have on('click) events and jQuery selections strewn throughout my object and not in the bindEvents and cacheDOM functions.

Here is a fiddle with a simplified example of the problem: https://jsfiddle.net/6L2ry6hr/

In the above example it is not to bad... but as my apps get more complex it is becoming a bit of a hassle.

Jethro Hazelhurst
  • 3,230
  • 7
  • 38
  • 80

1 Answers1

1

Now imagine I want to bind a click event to an element in a Mustache template

I obviously can't do that on page load because the template is not rendered yet.

The requirement is possible using jQuery. The .innerHTML of a <script> element can be passed to jQuery() with an event and event handler attached.

jQuery.holdReady(true);
var template = jQuery($("#template").html());
// template.filter("element").on("event", function() {// do stuff})
jQuery("body").append(template);
jQuery.holdReady(false);
jQuery(function() {
  // do stuff
})
guest271314
  • 1
  • 15
  • 104
  • 177