从嵌套函数返回

时间:2015-09-29 04:08:17

标签: javascript function meteor

我尝试通过给定的URL检查(在模板的帮助器中)是否存在图像。

如果文件存在,我想将空格键设置为此URL。 如果它不存在,则应返回另一个URL。

我的问题是从onload- / onerror-函数返回:

Template.backgroundImage.helpers({
    image: function() {
        var url = '/background/'+file+'.jpg';

        var img = new Image();
        img.onload = function() { return url; }
        img.onerror = function() { return '/background/image.jpg'; }
        img.src = url;
    }
});

<template name="backgroundImage">
    <img src="{{image}}">
</template>

2 个答案:

答案 0 :(得分:0)

你可以使用Promise:

Template.backgroundImage.helpers({
  image: function() {
    return new Promise(function(resolve) {
      var img = new Image();
      var url = '/background/' + file + '.jpg';
      img.addEventListener('load', function() { resolve(url); });
      img.addEventListener('error', function() { resolve('/background/image.jpg'); });
      img.src = url;
    });
  }
});

答案 1 :(得分:0)

您可以使用Template onRendered回调来更新错误的图像SRC:

Template.backgroundImage.helpers({
    image: function() {
        return '/background/'+file+'.jpg';
    }
});

Template.backgroundImage.onRendered(function(){
    var $img = this.$('img'); //Whatever your selector is, not sure if this.$ works in onRendered though

    // "one" makes sure event is only fired once, see below
    $img.one("error", function() {
     $img.attr('src','/background/image.jpg')
    });

    // If image was loaded, reload it
    // This is usually used to check if images were loaded from cache
    // but as you only want to track errors, it's probably unnecessary 
    if($img.get().complete) {
        $img.load();
    }
})