Meteor如何在订阅准备好时调用函数

时间:2017-05-17 06:55:05

标签: meteor

当订阅准备就绪时,Meteor客户端代码需要调用函数openNewTab(age);,因为mongodb文档将参数提供给该函数age。我已经不记得我尝试了多少东西。谁可以做到? THX

    //client/main.js
    Meteor.startup(function () {
      Tracker.autorun(function () {
        Meteor.subscribe('myCol', Session.get('age'));
      });
    });

//client/lib.js

Template.footer.events({
  'click #submit': (event) => {
    event.preventDefault();
    lib.usageEntry({taskSelected: taskSelected});
  }
});
const lib = {
  'usageEntry': function (Obj) {
    // do stuff
    lib[Obj.taskSelected]();  // task1
  },
  'task1': function () {
    let age = document.getElementsByClassName('age')[0].text()
    Session.set('age', age);  // so the reactive subscription works
    openNewTab(age);  //<=== how can this wait till subscription is ready?
  }
}


    //server
    Meteor.publish('myCol', function (age) {
      if (!this.userId || Meteor.users.findOne({_id:this.userId}).profile.notOk) return;
      if (Meteor.users.findOne({_id:this.userId}).profile.hasOwnProperty('notPaid')) return;
      let matcher = new RegExp('[0-9]{1,3}', "gi");
      if (matcher.test(age)) {
        return myCol.find({age: age}, {
          fields: {
            propName: true,
          }, limit: 1
        });
      }
    });

1 个答案:

答案 0 :(得分:1)

您实际上可以提供对subscribe函数的回调,该函数将在订阅完成后执行。

e.g。

const HomeStuffCollection = new Mongo.Collection('homeStuff')

if (Meteor.isClient) {
  const doSomething = (data) => { /* do stuff */ }

  Template.home.onCreated(function() {
    this.subscribe('homeStuff', () => {
      doSomething(HomeStuffCollection.find().fetch())
    })
  })
}

if (Meteor.isServer) {
  Meteor.publish('homeStuff', function() {
    return HomeStuffCollection.find()
  })
}

文档:https://docs.meteor.com/api/pubsub.html#Meteor-subscribe