typescript - 我可以在回调本身中结束 firebase 回调吗?
问题描述
我想知道是否有任何方法可以在回调本身内停止回调。我已经尝试使用 ref.off() 方法来停止它,如下所示,但它仍会继续运行。有什么建议么?
ref.orderByChild('t').startAt(time.getTime()).on('child_added', function (snapshot) {
const d = snapshot.val();
const x = Math.round(d.x * 100).toString();
const y = Math.round(d.y * 100).toString();
if (that.selectedEnd && d.t > that.selectedEnd.getTime()) {
snapshot.ref.off('child_added');
console.log('STOP');
} else {
....
}
});
解决方案
根据 API 文档on()
:
返回函数
提供的回调函数未经修改返回。如果您想将内联函数传递给 on() 但存储回调函数以供稍后传递给 off(),这只是为了方便。
因此,您可以将其返回值传递给off()
, 在您调用的同一 Query 对象上调用on()
:
const query = ref.orderByChild('t').startAt(time.getTime());
const listener = query.on('child_added', function (snapshot) {
...
query.off('child_added', listener);
});
推荐阅读
- javascript - React 和 node js 表单图片提交
- google-analytics - 是否可以从 Google Analytics 中选择性地删除数据(特定页面 URL)?
- .net - React SPA + .NET CORE + AuthorizationHandler
- javascript - 如何更改输入文本并在之后存储它?
- xml - ODI-40854:未提供用于同步的文件。使用创建文件
从 命令 - php - 从文本文件中提取某些数据并创建表格
- spring-data - 如何一起使用 spring-data-ldap 和 spring-security-ldap?
- powershell - 如何通过Powershell将文件共享中网站下的普通文件夹转换为应用程序?
- html - 将卡片内容与其他卡片内容对齐(照片)
- javascript - 有没有办法在基于地区设置货币时获得一致的输出