这里不会有开箱即用的反应性。Meteor 方法不是响应式的,而只是对返回某些内容的服务器(rpc-)端点的包装 ddp 调用。
为了从服务器获取响应式数据,您需要订阅发布。如果您只想发布此计数器,您可以创建一个包含单个文档的集合并发布它。
进口/CountCollection.js(两者)
export const CountCollection = new Mongo.Collection('myCounter')
server/counter.js(服务器)
import { CountCollection } from '../imports/CountCollection'
let counterDocId
Meteor.startup(() => {
// optional: clear the collection on a new startup
// this is up to your use case
// CountCollection.remove({})
// create a new counter document
counterDocId = CountCollection.insert({ count: 0 })
// use the Meteor.setInterval method in order to
// keep the Meteor environment bound to the execution context
// then update the counter doc each second
Meteor.setInterval(function () {
CountCollection.update(counterDocId, { $inc: { count: 1 } })
}, 1000)
})
// Now we need a publication for the counter doc.
// You can use the `limit` projection to restrict this to a single document:
Meteor.publish('counterDoc', function () {
if (!counterDocId) this.ready()
return CountCollection.find({ _id: counterDocId }, { limit: 1 })
})
现在您可以订阅此出版物并获得对文档的响应式更新:
客户端/someData.js(客户端)
import { CountCollection } from '../imports/CountCollection'
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { Tracker } from 'meteor/tracker'
import './main.html';
// Setup reactive variable
const reactiveCounter = new ReactiveVar(0)
const counterSubscription = Meteor.subscribe('counterDoc')
Template.someData.onCreated(() => {
const instance = this
instance.autorun(() => {
// counterSubscription.ready() will re-called
// when the publication released a new cursor
// which causes the autorun to re-run = reactivity
if (counterSubscription.ready()) {
// there is only 1 doc published, so no query require
const counterDoc = CountCollection.findOne()
reactiveCounter.set(counterDoc && counterDoc.count)
}
})
})
// Display the output from reactiveVar
Template.someData.helpers({
someData: function() {
return reactiveCounter.get()
}
})
边注:
不要忘记获取正确的路径和导入
读数:
https://docs.mongodb.com/manual/reference/operator/update/inc/
https://docs.meteor.com/api/timers.html#Meteor-setInterval