2013-02-01 155 views
12

有什么办法可以订阅流星计数。流星订阅计数

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

+3

你可能想读这个条目:http://stackoverflow.com/questions/10565654/how-does-the-messages-count-example-in-meteor-docs-work – machour

+2

你有已经回答了您的问题:-) –

回答

16

我有下面的代码来发布我的柜台

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 
+0

在APM博客上看到一个链接。尼斯 – Harry

+0

@Harry Care加入链接? – Choy

+0

@Choy,这里是哈里正在谈论的链接:https://kadira.io/academy/reducing-pubsub-data-usage/ –

8

Meteor文档实际上展示了一个很好的例子,说明如何使用更新的观察API来完成此操作。我在这里重新发布它,但原始文档在这里:http://docs.meteor.com/#meteor_publish

Meteor.publish("counts-by-room", function (roomId) { 
    var self = this; 
    var count = 0; 
    var initializing = true; 
    var handle = Messages.find({roomId: roomId}).observeChanges({ 
    added: function (id) { 
     count++; 
     if (!initializing) 
     self.changed("counts", roomId, {count: count}); 
    }, 
    removed: function (id) { 
     count--; 
     self.changed("counts", roomId, {count: count}); 
    } 
    // don't care about moved or changed 
    }); 

    // Observe only returns after the initial added callbacks have 
    // run. Now return an initial value and mark the subscription 
    // as ready. 
    initializing = false; 
    self.added("counts", roomId, {count: count}); 
    self.ready(); 

    // Stop observing the cursor when client unsubs. 
    // Stopping a subscription automatically takes 
    // care of sending the client any removed messages. 
    self.onStop(function() { 
    handle.stop(); 
    }); 
}); 

// client: declare collection to hold count object 
Counts = new Meteor.Collection("counts"); 

// client: subscribe to the count for the current room 
Meteor.autorun(function() { 
    Meteor.subscribe("counts-by-room", Session.get("roomId")); 
}); 

// client: use the new collection 
console.log("Current room has " + 
      Counts.findOne(Session.get("roomId")).count + 
      " messages.");