简体   繁体   中英

Firebase's Realtime Database's event listener's handler executes itself infinitely

I found next executing itself infinitely. I think this is an abstraction of my code that replicates the problem:

function next() {
  game.set(newObj)
}
game.child(`user1`).orderByKey().on(`value`, next);

The solution was to insert a remove the event listener:

game.child(`user1`).orderByKey().off() //new
function next() {
  game.set(newObj)
}
game.child(`user1`).orderByKey().on(`value`, next);

My initial understanding was ref.orderByKey().on('value', ...) executed its handler once. Is there anything you can see here that explains why the handler executed infinitely?

If not, perhaps another piece of code was responsible - like one of the child_changed event listeners I have. My child_changed listeners all listen for a change in various parts of game . Surely updating game to a new object would trigger them. However, none of their callbacks are next so I think they don't play a role in retriggering next .

My initial understanding was ref.orderByKey().on('value', ...) executed its handler once. Is there anything you can see here that explains why the handler executed infinitely?

No, that's exactly the way it's supposed to work. A listener attached using on() will be invoked every time the data is seen to change. It will continue to do so until the listener is removed. To do that, you must call off() after you call on() .

If you want to execute a query just once , use once() instead of on() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM