如何防止已发布集的客户端发生“价值”事件?

kof*_*fus 5 javascript firebase firebase-realtime-database

Firebase客户端调用set()将导致所有连接的客户端都已value触发- 包括 -发出的原始客户端set()

就我而言(并且我认为在大多数情况下),发出的客户没有理由set()响应其自身调用产生的价值事件。显然,它的模型是正确的,不需要更改它(这可能是昂贵的操作)。

客户端是否可以通过某种方式不接收/阻止/忽略value其自身set()调用触发的事件?我考虑过使用开/关,set()但这样会使客户端错过value同时发生但未被触发的事件。

我是否缺少明显的东西?

Fra*_*len 8

大多数应用程序将Firebase数据本身视为模型。因此,当有更新时,他们会调用ref.set()(或另一个mutator函数),然后该更新会通过一个on()事件流回到其应用程序中。React / Flux爱好者将其称为单向数据流,其他人可能将其称为“ 命令查询责任隔离”

但是确实确实存在某些情况,其中模型已经更新,因此如果您是触发它的人,则希望忽略Firebase中的事件。

没有API用于不接收这些自触发事件。相反,您必须“记住”发送给Firebase的数据,并在on()处理程序中将其过滤掉。

Firebase的Android绘图示例保留了发送到Firebase的线段列表,然后在其onChildAdded处理程序中忽略了这些线段。它使用推式ID标识线段,并且这些线段是在客户端生成的,因此它可以使用推式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
    }
});
Run Code Online (Sandbox Code Playgroud)


kof*_*fus 1

我最终在模型中添加了一个客户端 ID,如下所示:

var clientId=(Math.random()*10000000000000000).toFixed(0);

function set(data) {
    ref.set(JSON.stringify({ clientId: clientId, data: data }));
}

ref.on('value', function(snapshot) {
    var json=JSON.parse(snapshot.val());
    if (!json || json.clientId===clientId) return;

    var data=json.data;
    // update model with data
});
Run Code Online (Sandbox Code Playgroud)