流星订阅计数 [英] Meteor subscribe to a count

查看:13
本文介绍了流星订阅计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方法可以订阅meteor中的计数.

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

我想发布 Articles.find().count() 而不是发布 Articles.find().理想情况下,这应该将计数分配给一个反应性会话,该会话会在计数变化时发生变化.

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.

推荐答案

我有以下代码来发布我的计数器

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()

我是这样使用的:

  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

这篇关于流星订阅计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆