如果使用Javascript更改Firebase数据,如何调用函数

时间:2018-05-09 07:38:06

标签: javascript firebase web firebase-realtime-database

我需要在javascript中Firebase值更改时调用函数, 我尝试在Javascript中寻找像onDataSetChanged这样的函数,但没有找到任何函数。

1 个答案:

答案 0 :(得分:3)

使用firebase.database.Reference的on()或once()方法观察事件,详见此处:https://firebase.google.com/docs/database/web/read-and-write#listen_for_value_events

例如你可以这样做:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
  yourFunction();  //<- call your function here
});

var starCountRef = firebase.database().ref('posts/' + postId);
starCountRef.on('value', function(snapshot) {
  yourFunction(snapshot.val().postAuthor);  //<- example, we pass the author of the Post to the function
});

如果要将快照中的值作为函数的参数传递