2015-08-19 21 views
2

Firebase客户端调用set()将导致所有连接的客户端触发value - 包括 - 发出set()的原始客户端。如何防止发布set的客户端发生'value'事件?

在我的情况下(我认为在大多数情况下),发布set()的客户端没有理由对自己的调用产生的值事件作出响应。显然它的模型是正确的,不需要改变它(这可能是一个昂贵的操作)。

有什么办法让客户端不接收/阻止/忽略由其自己的set()调用触发的value事件?我考虑在set()附近使用off/on,但这可能会使客户错过value同时发生但未由其触发的事件。

我错过了一些明显的东西吗?

回答

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 
}); 
4

大多数应用程序将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 
    } 
}); 
+0

THX弗兰克,我学到了很多你的答案 – kofifus