如何丢弃 Firebase 数据库中的初始数据 [英] how to discard initial data in a Firebase DB

查看:22
本文介绍了如何丢弃 Firebase 数据库中的初始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的应用程序,通知客户其他客户点击了一个按钮.我使用以下命令将点击次数存储在 Firebase (db) 中:

I'm making a simple app that informs a client that other clients clicked a button. I'm storing the clicks in a Firebase (db) using:

db.push({msg:data});

所有客户端都会通过 on 获得其他用户点击的通知,例如

All clients get notified of other user's clicks with an on, such as

db.on('child_added',function(snapshot) { 
  var msg = snapshot.val().msg; 
});

但是,当页面第一次加载时,我想丢弃堆栈中的任何现有数据.我的策略是在定义 db.on('child_ added',...) 之前调用 db.once() 以获得初始子代数,然后使用它来丢弃对 db.on('child_ added',...) 的调用次数.

However, when the page first loads I want to discard any existing data on the stack. My strategy is to call db.once() before I define the db.on('child_added',...) in order to get the initial number of children, and then use that to discard that number of calls to db.on('child_added',...).

不幸的是,所有对 db.on('child_added',...) 的调用都发生在 之前 我能够获得初始计数,所以它失败了.

Unfortunately, though, all of the calls to db.on('child_added',...) are happening before I'm able to get the initial count, so it fails.

如何有效且简单地丢弃初始数据?

How can I effectively and simply discard the initial data?

推荐答案

如果我正确理解您的问题,听起来您想要自用户访问页面以来添加的数据.在 Firebase 中,您描述的行为是设计使然,因为数据总是在变化,并且没有旧"数据与新"数据的概念.

If I understand your question correctly, it sounds like you only want data that has been added since the user visited the page. In Firebase, the behavior you describe is by design, as the data is always changing and there isn't a notion of "old" data vs "new" data.

但是,如果您只想显示页面加载后添加的数据,请尝试忽略之前的所有事件,直到完整的子项集至少加载一次.例如:

However, if you only want to display data added after the page has loaded, try ignoring all events prior until the complete set of children has loaded at least once. For example:

var ignoreItems = true;
var ref = new Firebase('https://<your-Firebase>.firebaseio.com');
ref.on('child_added', function(snapshot) {
  if (!ignoreItems) {
    var msg = snapshot.val().msg;
    // do something here
  }
});
ref.once('value', function(snapshot) {
  ignoreItems = false;
});

这种方法的替代方法是编写具有优先级的新项目,其中优先级是 Firebase.ServerValue.TIMESTAMP(当前服务器时间),然后使用 .startAt(...) 使用当前时间戳查询.然而,这比上述方法更复杂.

The alternative to this approach would be to write your new items with a priority as well, where the priority is Firebase.ServerValue.TIMESTAMP (the current server time), and then use a .startAt(...) query using the current timestamp. However, this is more complex than the approach described above.

这篇关于如何丢弃 Firebase 数据库中的初始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆