javascript - 新记录出现在表格底部?

标签 javascript meteor

我有一个 meteor 应用程序,它使用以下代码在表格中显示记录:

Template.records.helpers({
  trackingData: function() {
    return Tracking.find({},{$sort: {fullDate: -1}})
  }
})

<table>
  ...
  {{#each trackingData}}
     <tr class="record" id="{{_id._str}}">
     ...
  {{/each}}
  ...
</table>

Meteor.publish('tracking', function(filter, offset) {
    var records = Tracking.find(filter,{
      sort: {fullDate: -1}, 
      limit:10, 
      skip: offset*10
    });
    return records
  });

出于某种原因,当我添加新记录时,它总是显示在表格的底部。根据我的排序,新记录应该显示在顶部。奇怪的是,当我刷新页面时,记录保留在底部但是当我停止我的应用程序并重新启动它时 - 记录显示在顶部,就像它应该的那样。我可能遗漏了什么会导致这种奇怪的排序行为?

最佳答案

您可能想使用 Tracker.flush()或类似的:

Normally, when you make changes (like writing to the database), their impact (like updating the DOM) is delayed until the system is idle. This keeps things predictable — you can know that the DOM won’t go changing out from under your code as it runs. It’s also one of the things that makes Meteor fast.

Tracker.flush forces all of the pending reactive updates to complete. For example, if an event handler changes a Session variable that will cause part of the user interface to rerender, the handler can call flush to perform the rerender immediately and then access the resulting DOM

基本上,Collection.find操作返回一个通常只计算一次的游标。

this blog 涵盖了该主题还有:

When you publish documents to the client, they are merged with other documents from the same collection and rearranged into an in-memory data store called minimongo. The key word being rearranged.

Many new meteor developers have a mental model of published data as existing in an ordered list. This leads to questions like: "I published my data in sorted order, so why doesn't it appear that way on the client?" That's expected. There's one simple rule to follow:

If you need your documents to be ordered on the client, sort them on the client. Sorting in a publish function isn't usually necessary unless the result of the sort changes which documents are sent (e.g. you are using a limit).

You may, however, want to retain the server-side sort in cases where the data transmission time is significant. Imagine publishing several hundred blog posts but initially showing only the most recent ten. In this case, having the most recent documents arrive on the client first would help minimize the number of template renderings.

关于javascript - 新记录出现在表格底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48781264/

相关文章:

mongodb - 从 GUI 连接到 Meteor Mongo

javascript - Meteor 应用程序中没有访问控制允许来源错误

c# - 在asp.net mvc 3中显示倒计时器

javascript - 从服务器写入文件返回成功,但找不到文件

meteor - 依赖选择框 meteor

javascript - 完全可以用meteor来开发手机app吗

javascript - 如何在 Razor 中保存 ViewModel 的数组

javascript - 使用 HTML、CSS 和 JS 构建桌面应用程序的替代方案

javascript - 使用 jquery 在页面后加载广告(脚本)

javascript - jQuery - 如果浏览器选项卡获得焦点,则执行 AJAX - 不起作用