标签:javascript meteor
我正在尝试显示我的页脚中的用户数量,我希望实时显示这个数字.我认为正确的方法是在服务器中创建一个发布并从客户端订阅.
// 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>
在chrome控制台中,我们可以看到回调函数中的“订阅”字符串.问题是:{{famecoiners}}总是在我的模板中返回0.
解决方法:
发布所有用户都可以,但这不实用.如果您有10,000个用户怎么办?你真正想要做的是创建一个客户端集合,它只包含一个代表计数的项目.如果您查看文档的Publish and subscribe部分中的第二个示例,您将看到执行此操作的内容.我将在下面提供一个完整的工作示例:
$meteor create test
$cd test
$rm test.*
$mkdir server client
$meteor remove autopublish
$meteor add coffeescript
客户机/ client.coffee
# 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
服务器/ server.coffee
# 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
对不起,如果您不喜欢CoffeeScript – 我希望代码紧凑.
$meteor start
如果您打开控制台,您将看到用户数增加.为了好玩,您可以打开mongo shell并运行db.users.remove();并观看它重置.
标签:javascript,meteor 来源: https://codeday.me/bug/20190926/1821909.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。