【问题标题】:Meteor JS execute JQuery after mongodb.find()Meteor JS 在 mongodb.find() 之后执行 JQuery
【发布时间】:2017-08-14 15:01:48
【问题描述】:

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

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

问题是 find() 方法被异步调用,所以在模板从 db 获取数据之前调用了 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({})
    }
})

【问题讨论】:

  • 那么...在回调中运行您的 jQuery 命令?你应该向我们展示你的作品。

标签: jquery mongodb meteor meteor-blaze


【解决方案1】:

在 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,它提供了其他一些不同的订阅模式,例如这个。

【讨论】:

  • var template = this;它是干什么用的??
  • 只是尝试更详细地说明.subscribeTemplate 对象的原型方法(这是所有模板回调的上下文...例如@987654329 @ 目的)。在一天结束时,您可以放弃var 并致电this.subscribe
猜你喜欢
  • 1970-01-01
  • 2011-09-09
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2021-08-24
  • 1970-01-01
相关资源
最近更新 更多