Meteor.startup在客户端
当在客户端使用以下代码时,为什么if(init)
的variablesinit
被评估为true
即使它在init = true
之前,并且没有新文档添加到Orders
集合中? 这会导致query.observe
返回查询返回的所有文档,而不仅仅是新添加的文档。
在服务器端没有发现这种行为,只在添加新文档时才执行console.log
。
Meteor.startup(function() { var init = false var query = Orders.find() var handle = query.observe({ added: function (doc) { if(init) console.log(doc) } }); init = true })
这是因为在服务器上一切都是同步的,而客户端上的一切都是asynchronous的 。
在query.observe
操作完成后, init=true
将被设置,但是在客户端上它可以被设置,因为init
将被设置为true
几乎与观察句柄运行一样。
你将不得不使用一种不同的行为来使其按照客户期望的方式工作。
也许在订阅完成后使用获取时间戳的东西,然后只有在当前时间戳较高时才继续:
Meteor.subscribe("yourdocs", function() { Session.set("yourdocs_finishtime", new Date().getTime()); });
然后你添加的句柄:
added: function (doc) { var subtime = Session.get("yourdocs_finishtime"); if(subtime && (subtime < new Date().getTime())) console.log(doc); }