车把和异步通话 [英] Handlebars and async call

查看:65
本文介绍了车把和异步通话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此帮助程序检查图像是否存在:

I use this helper to check wether an image exists or not:

Handlebars.registerHelper('checkLogo', function(url) {

      UrlExists(url, function(status){
      if(status === 200){    
       return new Handlebars.SafeString(url)
      }
      else if(status === 404){        
        console.log('no logo found');
      }
});
});


function UrlExists(url, cb){
    $.ajax({
        url:      url,
        dataType: 'text',
        type:     'GET',
        complete:  function(xhr){
            if(typeof cb === 'function')
               cb.apply(this, [xhr.status]);
        }
    });
}

我在模板中这样称呼它(URL为arg),

I call it (with a url as arg) in my template like this:

<img src="{{checkLogo logo}}"/>

我希望{{checkLogo logo}}被url代替,但是什么也不会返回.

Im expecting {{checkLogo logo}} to be replaced by the url but nothing gets returned. Is it maybe beacuse of the async action and because of this it has to be handled differently?

谢谢

推荐答案

尽管Handlebars不支持异步帮助器,您仍然可以使用帮助器来实现这一点.使用帮助程序创建一些独特的html,并使用 MutationObserver来检测它是否已添加到DOM中. .然后,您可以保留添加的img元素,并根据需要进行修改.

Though Handlebars doesn't support asynchronous helpers you can still use helpers to achieve this. Create some unique html with a helper and detect it being added to the DOM using MutationObserver. Then you can get a hold of the added img element and modify it however you like.

一个更简单,更有效的解决方案是使用img元素的onerror属性来触发一些回调. 这是一个小提琴示例. 另一把小提琴,它使用车把模板.

A much simpler and more efficient solution would be to use the onerror attribute of img element to trigger some callback. Here's an example fiddle. Another fiddle that uses a handlebars template.

如果您想探索Handlebars + MutationObserver的方式,我已经创建了一个可以使用或适应的助手.可在 https://github.com/ekuusela/post-render-bars 和在此小提琴中进行了演示.

If you want to explore the Handlebars + MutationObserver way, I've created a helper that you can use or adapt. It's available at https://github.com/ekuusela/post-render-bars and demonstrated in this fiddle.

watch.js 定义了函数在DOM中遇到给定的html时会触发回调.它将html修改为暂时具有使其独特的类.

watch.js defines a function forHtml(html, callback) which triggers a callback when the given html is encountered in the DOM. It modifies the html to temporarily have a class that makes it unique.

helpers.js 定义了帮助器和函数createRenderer(getHtmlContentFn),它将您的函数包装到渲染器中,可以将其传递到模板中并用作帮助器的参数.

helpers.js defines the helper renderer and the function createRenderer(getHtmlContentFn) which wraps your function into a renderer and that can be passed in to a template and used as an argument for the helper.

这篇关于车把和异步通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆