2013-02-01 191 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.");