How to retrieve only new data?

2019-01-02 18:11发布

I'm trying to create simple notification system for my site admin, and I need to send only real-time messages to every admin user. But when I use firebase it loads old data on every page, and user see all messages from database. If I set limit(1) user will see last notification on every page reloading:

var eventsList = new Firebase('https://*****-messages.firebaseio.com/');

eventsList.on('child_added', function(message) {
    var message = message.val();
    $.notification(message.message);
});

How I can load only new messages, without old notification history?

标签: firebase
2条回答
还给你的自由
2楼-- · 2019-01-02 18:49

This is by design, in a real-time system there is no concept of the "latest" data because it's always changing. However, if you want to only display items added to the list after the page has loaded, you can do the following:

var newItems = false;
var eventsList = new Firebase('https://*****-messages.firebaseio.com/');

eventsList.on('child_added', function(message) {
  if (!newItems) return;
  var message = message.val();
  $.notification(message.message);
});
eventsList.once('value', function(messages) {
  newItems = true;
});
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-02 19:15

I would comment on the above, but due to reputation I cannot, so hoping this is adequate and this is to address the last comment by Gruff McGruff.

Once fires after because you want to break out of the loop of grabbing all child items. Once that loops is broken, you'll set the newItems variable to true, and then it will be able to get all new children after that.

If you fired it before, it would defeat the purpose and grab all child items regardless because you'll set the newItems variable immediately.

Also, I've used this approach and it works well.

查看更多
登录 后发表回答