Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there any way to subscribe to a count in meteor.

I want to publish Articles.find().count() rather than publish Articles.find(). Ideally this should assign the count to a reactive Session that would change when the count changes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...