大多数应用程序将Firebase数据本身视为其模型。因此,当有更新时,他们会呼叫ref.set()
(或另一个增变函数),然后更新通过on()
事件流回其应用程序。 React/Flux爱好者知道这是unidirectional data-flow,其他人可能知道它是Command Query Responsibility Segregation。
但确实存在模型已经更新的情况,因此如果您是触发Firebase的事件,则您希望忽略该事件。
没有接收这些自触发事件的API。相反,您必须“记住”您发送给Firebase的数据,并在您的on()
处理程序中对其进行过滤。
Android图纸样本来自Firebase keeps a list of segments that it sends to Firebase,然后是ignores those segments in its onChildAdded
handler。它使用push id识别线段,并且这些线段是在客户端生成的,因此它可以使用这些线段来跟踪识别线段。
这
一个JavaScript样本:
var pendingChildIds = []; // Push ids of nodes we've sent to the server, but haven't received in `on()` yet
// this code is in your UI event handler, or whatever triggers the needs to update your Firebase data
var newChild = ref.push();
pendingChildIds.push(newChild.key());
newChild.set(
{ property1: 'value1', property2: 3.14 },
function(error) {
// the write operation has completed, remove the child id from the list of pending writes
pendingChildIds.splice(pendingChildIds.indexOf(newChild.key());
}
);
// this is the event handler, using child_added in this case
ref.on('child_added', function(snapshot) {
if (!pendingChildIds.contains(snapshot.key())) {
// this is a child that we DIDN'T generate
}
});
THX弗兰克,我学到了很多你的答案 – kofifus