Does Handlebars.registerHelper support async funct

2019-07-14 00:07发布

问题:

Is it possible to create a Handlebars Helper Function that returns async result? Maybe Handlebars supports some kind of two way binding? I want to use JSON data from JSONP request so jQuery.ajax also does not support async: false, but however this would not be exactly the same that I am looking for.

回答1:

You can call whatever functions you want in a helper but that won't do you any good. The problem is that Handlebars helpers work with strings and someone else will convert those strings to DOM elements. But, by the time your AJAX call finishes, there won't be any useful connection between the DOM elements that were built based on the string that Handlebars produced and any context that you can capture in a success callback inside a helper.

I think the best you can do is break it into two pieces:

  1. The helper function can produce HTML with a desired structure, you'd probably have some combination of class and data-* attributes for the structure.
  2. Some JavaScript that acts on the HTML after it has been DOMified. This JavaScript could look for things with the class and data-* attributes from 1, launch the appropriate AJAX calls, and then patch up the DOM in the success handlers.

Maybe not that helpful but that's probably the best you can do when working with a text-based template system.