Firebase child_added只会添加子项

时间:2012-08-03 03:35:53

标签: firebase

来自Firebase API:

  

已添加儿童:此活动将针对每个初始儿童触发一次   在这个位置,它会在每次新的时候再次触发   孩子被添加。

一些代码:

listRef.on('child_added', function(childSnapshot, prevChildName) {
    // do something with the child
});

但是,由于该位置的每个孩子都会调用该函数,有没有办法只获取实际添加的孩子?

6 个答案:

答案 0 :(得分:37)

要跟踪自某个检查点以来添加的内容而不提取以前的记录,您可以使用endAt()limit()来获取最后一条记录:

// retrieve the last record from `ref`
ref.endAt().limitToLast(1).on('child_added', function(snapshot) {

   // all records after the last continue to invoke this function
   console.log(snapshot.name(), snapshot.val());

});

答案 1 :(得分:36)

不推荐使用

limit()方法。 limitToLast()limitToFirst()方法取代了它。

// retrieve the last record from `ref`
ref.limitToLast(1).on('child_added', function(snapshot) {

   // all records after the last continue to invoke this function
   console.log(snapshot.name(), snapshot.val());
   // get the last inserted key
   console.log(snapshot.key());

});

答案 2 :(得分:3)

我尝试了其他答案,但至少为最后一个孩子调用了一次。如果您的数据中有时间密钥,则可以这样做。

MyConnection = New System.Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & indlg.FileName & ";Extended Properties=Excel 8.0"))

答案 3 :(得分:2)

由于在没有数据的情况下调用ref.push()方法会根据时间生成路径键,这就是我所做的:

// Get your base reference
const messagesRef = firebase.database().ref().child("messages");

// Get a firebase generated key, based on current time
const startKey = messagesRef.push().key;

// 'startAt' this key, equivalent to 'start from the present second'
messagesRef.orderByKey().startAt(startKey)
.on("child_added", 
    (snapshot)=>{ /*Do something with future children*/}
);

请注意,实际上没有任何内容写入ref.push()返回的引用(或“键”),因此无需捕获空数据。

答案 4 :(得分:1)

Swift3解决方案:

您可以通过以下代码检索以前的数据:

    queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
        //Your code

    })

然后通过以下代码观察新数据。

queryRef?.queryLimited(toLast: 1).observe(.childAdded, with: { (snapshot) in

 //Your Code

        })

答案 5 :(得分:0)

由于.limitToLast()方法仍然调用列表中的最后一项,即使它不是新项,我们也可以按以下方式解决它:

想法是:

创建一个列表,保留您的Firebase物品;每当调用onChildAdded(...)方法时,检查传入的数据快照是否在您的列表中;如果没有,那就是新数据

  

要实现这一目标,您必须满足以下条件:

  1. 每个项目都有唯一的值。 (这可以通过使用.push()方法生成的密钥将项目添加到Firebase中来实现。

  2. 重写模型类的.equals()方法,以便基于此唯一值完成比较。

代码段

注意:我将选择的项目列表放在模型类中。

模型类

public class MyModel {

    private String id; // unique ID from model to another
    public static List<MyModel> sItems; // my tracked items

    // reset of fields ...


    public MyModel() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


    @Override
    public boolean equals(@Nullable Object o) {

        // If the object is compared with itself then return true
        if (o == this) {
            return true;
        }

        // Check if o is an instance of MyModel or not
        if (!(o instanceof MyModel)) {
            return false;
        }

        // typecast o to MyModel so that we can compare data members
        MyModel model = (MyModel) o;

        // Compare data based on the unique id
        return (model.id).equals(id);
    }

}

Firebase监听器

private ChildEventListener mChildEventListener = new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

        Log.d(TAG, "ChildEventListener: onChildAdded()");

        MyModel deal = dataSnapshot.getValue(MyModel.class);
        if (!MyModel.sItems.contains(model)) {
            // Here you'll receive only the new added values
        }

    }

    @Override
    public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        Log.d(TAG, "ChildEventListener: onChildChanged()");
    }

    @Override
    public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
        Log.d(TAG, "ChildEventListener: onChildRemoved()");
    }

    @Override
    public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        Log.d(TAG, "ChildEventListener: onChildMoved()");
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, "ChildEventListener: onCancelled()");
    }
};

然后限制到最后

databaseReference.limitToLast(1).addChildEventListener(mChildEventListener);
相关问题