Meteor JS在mongodb.find()之后执行JQuery

时间:2017-03-22 13:11:18

标签: jquery mongodb meteor meteor-blaze

我正在使用meteor js,现在我遇到了问题。

我想从我的mongodb中找到一些对象,之后我想执行一个jquery函数。

问题是find()方法被称为异步,因此在模板从数据库获取数据之前调用jquery函数。

那我该怎么办?

Template.dashboard.onRendered( function() {
//--- Slick Init ------
    $('.carousel').slick({
        infinite: false,
        dots: false,
        draggable: false,
        arrows: false,
        slidesToShow: 5,
        slidesToScroll: 1,
    });
})

Template.dashboard.helpers({

    devices() {
        return Devices.find({})
    }
})

1 个答案:

答案 0 :(得分:0)

在Meteor中,如果您想在订阅完成时或在.find返回数据时初始化插件,那么您应该遵循以下模式。

Template.listing.onRendered(function () {
  var template = this;

  // Subscribe to data
  template.subscribe('listOfThings', () => {
    // Wait for the data to load using the callback to subscribe

    // Execute​ your collection .find()

    Tracker.afterFlush(() => {
      // Use Tracker.afterFlush to wait for the UI to re-render
      // then initialize your jquery component

      // Initialization code here
    });
  });
});

如果您正在初始化的组件不依赖于直接执行.find(),而是依赖于您的模板首先运行帮助程序,那么您将遵循非常类似的模式。唯一的区别是你根本不会执行.find()

Template.listing.onRendered(function () {
  var template = this;

  // Subscribe to data
  template.subscribe('listOfThings', () => {
    // Wait for the data to load using the callback to subscribe

    Tracker.afterFlush(() => {
      // Use Tracker.afterFlush to wait for the UI to re-render
      // (this will ensure your ui has already executed its template helper),
      // then initialize your jquery component

      // Initialization code here
    });
  });
});

显然,您需要更改上面的代码才能使用您的特定模板名称和订阅名称。这只是为了描述您将遵循的特定模式。

我还建议您查看Blaze API manual,其中提供了一些其他各种订阅模式,例如此类。

相关问题