0
<div id="app"></div>
<script>
compileTemplate = function (source) {
  var template = Handlebars.compile(source);

  function parseJSON(id, data) {
    $(id).html(template(data));
  }

  parseJSON('#app', kingdom);
}
$.get('./templates/life.hbs', compileTemplate, 'html');
</script>

I'm trying to figure out how to rewrite this so that I don't have a nested function.

Here's what's going on.

  1. jQuery $.get uses compileTemplate function to compile the hbs file for html output.
  2. The parseJSON function uses the compiled template and inserts it into the element with the ID, app.

This works just fine, except I can't use parseJSON by itself because it relies on the template variable. Hence, I'm stuck nested and can't figure out how to fix it. If I take the template variable out of the function, then it doesn't work because it relies on source in the function. Bah, I always run into callback hell.

There's probably a better way to do all of this, but this is where I'm at after doing some research and trying to figure it all out.

Barry
  • 1,143
  • 2
  • 13
  • 26

1 Answers1

0

Well, it took me a while but I managed to refactor the code on my own. Thanks to anyone who was trying. Here's my solution:

function module(id, source, data) {
  $.get(source, function (source) {
    var template = Handlebars.compile(source);
    $(id).html(template(data));
  }, 'html');
}

module('#app', './templates/life.hbs', kingdom);

While there is still a nested function, it's organized such that it works in every purpose. This way, I can use the function module to pull in different hbs files and parse json through them without any extra work. Just simply inputting the ID of the element I want it to end up at, the source file, and the json data (which is being loaded by a script in the head of the page). Hope this is a useful function for someone. I am really happy with how it turned out.

Barry
  • 1,143
  • 2
  • 13
  • 26
  • Half of the battle was simply understanding what was going on in my first code sample. Lots of trial and error. In the end, the answer on this page (http://stackoverflow.com/questions/26643503/handlebars-loading-external-template-files) by Donovan S. really helped me. – Barry Aug 06 '15 at 21:08