简体   繁体   English

Handlebars.registerHelper是否支持异步功能?

[英]Does Handlebars.registerHelper support async functions?

Is it possible to create a Handlebars Helper Function that returns async result? 是否可以创建一个返回异步结果的Handlebars Helper Function? 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. 我想使用JSONP请求中的JSON数据,因此jQuery.ajax也不支持async:false,但是这与我要查找的不完全相同。

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. 问题在于,Handlebars助手使用字符串,其他人会将这些字符串转换为DOM元素。 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. 但是,到您的AJAX调用结束时,在基于Handlebars生成的字符串构建的DOM元素与您可以在辅助函数内的成功回调中捕获的任何上下文之间将没有任何有用的连接。

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. 辅助函数可以生成具有所需结构的HTML,您可能会对该结构具有classdata-*属性的某种组合。
  2. Some JavaScript that acts on the HTML after it has been DOMified. DOM化 ,一些可对HTML起作用的JavaScript。 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. 该JavaScript可以从1查找具有classdata-*属性的事物,启动适当的AJAX调用,然后在成功处理程序中修补DOM。

Maybe not that helpful but that's probably the best you can do when working with a text-based template system. 也许没有帮助,但这可能是使用基于文本的模板系统时可以做的最好的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM