【问题标题】:How to show the total count of items and a limit list of items on a same template如何在同一模板上显示项目总数和项目限制列表
【发布时间】:2015-01-27 06:29:15
【问题描述】:

我的页面上有两个部分。

第一部分的项目列表有限。第二部分有项目总数 (recordsCount)。

当服务器添加新项目时,我看到项目列表已更新,但总计数具有旧值。

Tracks = new Mongo.Collection('tracks')

客户:

Meteor.subscribe('tracks')

Meteor.call('records', function(err, data) {
    Session.set('_records', data)
})

Template.tracks.helpers({
    tracks: function() {
        return Tracks.find()
    },
    recordsCount: function() {
        return Session.get('_records')
    }
})

服务器:

Meteor.publish('tracks', function() {
    return Tracks.find({}, {limit: 100})
})

Meteor.methods({
    records: function() {
        return Tracks.find({}).count()
    }
})

var CronManager = new Cron(10000)
CronManager.addJob(1, function() {
    Tracks.insert({filed1: 'test'})
})

【问题讨论】:

标签: javascript meteor publish-subscribe meteor-helper


【解决方案1】:

如果您只想有效地将​​计数带入您的应用,请查看publish-counts 包。

Meteor.publish('posts', function(author) {
  var cursor = Tracks.find(...);
  Counts.publish(this, 'tracks-count', cursor, {nonReactive: true});
});

nonReactive 选项仅按需发送计数。如果您真的不需要实时计数,这可能很有用,因为大多数应用程序可以每隔几秒更新一次。这将节省大量 CPU。

Template.tracks.helpers({
  tracks: function() {
    return Counts.get('posts-count')
  }
});

来自Bulletproof Meteor, Counting Documents 的阿鲁诺达的精彩章节。

【讨论】:

  • 谢谢,我已经将我的服务器计数器代码包装在 Meteor.defer 中,例如 Meteor.defer(function() { Counts.publish(this, 'records-of-counter', Tracks.find() ) }.bind(this)) 但我认为避免 publish-counts 包是个好主意。
【解决方案2】:

我已经使用 publish-counts 包调查了解决方案。就我而言,它是非常重的包裹。它一直在加载CPU。我已将服务器端代码替换为使用带有计数字段的集合。

常见:

Counter = new Mongo.Collection('count')

服务器: Meteor.Publish('count', function() { 返回 Counter.find() })

if(Counter.find().count() === 0) Counter.insert({count: Tracks.find().count()})
var CronManager = new Cron(10000)
CronManager.addJob(1, function() {
    Counter.update({}, {$inc: {count: 1}})
    Tracks.insert({filed1: 'test'})
})

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多