$(document).ready(带有Meteor JS模板的function())

时间:2015-08-25 18:04:56

标签: javascript meteor

我有一个模板,我已经与Meteor深度整合。它使用一个scripts.js文件,它在$(document).ready和$(window).load之后运行一堆命令。

我将scripts.js放在客户端/兼容性中,并且只有在我对模板进行硬刷新时才有效。否则,模板不会渲染,函数也不会执行。

具体来说,这段代码:

    // Append .background-image-holder <img>'s as CSS backgrounds

$('.background-image-holder').each(function() {
    var imgSrc = $(this).children('img').attr('src');
    $(this).css('background', 'url("' + imgSrc + '")');
    $(this).children('img').hide();
    $(this).css('background-position', 'initial');
});

非常感谢,如果你知道我应该从这里采取它。

2 个答案:

答案 0 :(得分:5)

如果你想在DOM加载所有图像时启动一个函数,请使用:(预先警告,这是在ES6中)

let imgCount;
let imgTally = 0;

Template.myTemplate.onRendered(function () {
  this.autorun(() => {
    if (this.subscriptionsReady()) {
      Tracker.afterFlush(() => {
        imgCount = this.$('img').length;
      });
    }
  });
});

Template.myTemplate.events({
  'load img': function (event, template) {
    if (++imgTally >= imgCount) {
      (template.view.template.imagesLoaded.bind(template))();
    }
  }
});

然后你只需要声明imagesLoaded,它将在所有图像完成后被解雇。

Template.myTemplate.imagesLoaded = function () {
  // do something
};

答案 1 :(得分:3)

将这些东西放在模板的onRendered函数中。

Template.<name>.onRendered(function(){
//do your jquery business here!
});

For more info check the docs