我有以下代码来发布我的计数器
Meteor.publishCounter = (params) ->
count = 0
init = true
id = Random.id()
pub = params.handle
collection = params.collection
handle = collection.find(params.filter, params.options).observeChanges
added: =>
count++
pub.changed(params.name, id, {count: count}) unless init
removed: =>
count--
pub.changed(params.name, id, {count: count}) unless init
init = false
pub.added params.name, id, {count: count}
pub.ready()
pub.onStop -> handle.stop()
我是这样使用它的:
Meteor.publish 'bikes-count', (params = {}) ->
Meteor.publishCounter
handle: this
name: 'bikes-count'
collection: Bikes
filter: params
最后在客户端:
Meteor.subscribe 'bikes-count'
BikesCount = new Meteor.collection 'bikes-count'
Template.counter.count = -> BikesCount.findOne().count