我正在尝试显示我的页脚中的用户数量,我希望实时显示这个数字.我认为正确的方法是在服务器中创建一个发布并从客户端订阅.
// server/publications.js
Meteor.publish("usersCount", function () {
return Meteor.users.find();
});
// client/main.js
UsersCount = new Meteor.Collection("usersCount");
Meteor.subscribe('usersCount', [], function() {
console.log('subscribed.');
});
// client/views/layout/footer.js
Template.footer.helpers({
famecoiners: function(){
return UsersCount.find().count();
}
});
// client/views/layout/footer.html
<span>{{famecoiners}} Famecoiners!</span>
Run Code Online (Sandbox Code Playgroud)
在chrome控制台中,我们可以看到回调函数中的"订阅"字符串.问题是:{{famecoiners}}总是在我的模板中返回0.
Dav*_*don 13
发布所有用户都可以,但这不实用.如果您有10,000个用户怎么办?你真正想要做的是创建一个客户端集合,它只包含一个代表计数的项目.如果您查看文档的" 发布和订阅"部分中的第二个示例,您将看到执行此操作的内容.我将在下面提供一个完整的工作示例:
$ meteor create test
$ cd test
$ rm test.*
$ mkdir server client
$ meteor remove autopublish
$ meteor add coffeescript
Run Code Online (Sandbox Code Playgroud)
# Create a client-side subscription for the count of users.
UsersCount = new Meteor.Collection 'users-count'
Meteor.subscribe 'usersCount'
Meteor.startup ->
Meteor.setInterval (->
# To show something working, read the users count every second.
uc = UsersCount.findOne()
console.log uc.count or 0
), 1000
Run Code Online (Sandbox Code Playgroud)
# Create a 'Users' group for this demo instead of using accounts-password.
Users = new Meteor.Collection 'users'
Meteor.publish 'usersCount', ->
count = 0 # the count of all users
initializing = true # true only when we first start
handle = Users.find().observeChanges
added: =>
count++ # Increment the count when users are added.
@changed 'users-count', 1, {count} unless initializing
removed: =>
count-- # Decrement the count when users are removed.
@changed 'users-count', 1, {count}
initializing = false
# Call added now that we are done initializing. Use the id of 1 since
# there is only ever one object in the collection.
@added 'users-count', 1, {count}
# Let the client know that the subscription is ready.
@ready()
# Stop the handle when the user disconnects or stops the subscription.
# This is really important or you will get a memory leak.
@onStop ->
handle.stop()
Meteor.startup ->
# To show something working, insert a new user ever 0.5 seconds.
Meteor.setInterval (-> Users.insert {}), 500
Run Code Online (Sandbox Code Playgroud)
对不起,如果您不喜欢CoffeeScript - 我希望代码紧凑.
$ meteor start
Run Code Online (Sandbox Code Playgroud)
如果您打开控制台,您将看到用户数增加.为了好玩,您可以打开mongo shell并运行db.users.remove();并观看它重置.
| 归档时间: |
|
| 查看次数: |
6138 次 |
| 最近记录: |