I have following code to publish my counters
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()
and I use it like this:
Meteor.publish 'bikes-count', (params = {}) ->
Meteor.publishCounter
handle: this
name: 'bikes-count'
collection: Bikes
filter: params
and finally on client:
Meteor.subscribe 'bikes-count'
BikesCount = new Meteor.collection 'bikes-count'
Template.counter.count = -> BikesCount.findOne().count
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…