Cannot get key from datasnapshot

I am trying to get a snapshot key using

dataSnapshot.key()

but it does not seem to work. Here is the related code:

index.html

...

<select id="resList" size="20"></select>

...

index.js:

function addChild(name, id) {
    var list = document.getElementById("resList");
    var item = document.createElement("option");
    item.text = "Resolution " + id + ": " + name;
    list.add(item);
}

function changeChild(name, index) {
    var list = document.getElementById("resList");
    var item = document.createElement("option");
    item.text = "Resolution " + (index+1) + ": " + name;

    list.remove(index);
    list.add(item, index);
}

function removeChild(index) {
    var list = document.getElementById("resList");
    list.remove(index);
}

function init() {
    const resolutionRef = firebase.database().ref().child('resolutions');

    resolutionRef.on('child_added', function(childSnapshot, prevChildKey) {
        if (prevChildKey == null)
            prevChildKey = "0";

        addChild(childSnapshot.val(), parseInt(prevChildKey) + 1);
    });

    resolutionRef.on('child_changed', function(childSnapshot, prevChildKey) {
        if (prevChildKey == null)
            prevChildKey = "0";

        changeChild(childSnapshot.val(), parseInt(prevChildKey));
    });

    resolutionRef.on('child_removed', function(oldChildSnapshot) {
        removeChild(parseInt(oldChildSnapshot.key()));
    });
}

window.onload = init;

I have a child of a "root" link called "permissions". For each resolution, a new child is created with a reference to "resolution". Each permission has a name and an identifier. I store the identifier of each permission as a key, and its name as a value. This is convenient because in this way I can determine the permission index in "resList" by simply subtracting one of its keys.

The above code is great for adding and modifying children, but for some reason, when I delete a child, nothing happens.

Thanks for any help in advance!

+4
1

@FrankVanPuffelen, , "" , .

var key = dataSnapshot.key;

,

var key = dataSnapshot.key();

.

+6

Source: https://habr.com/ru/post/1651945/


All Articles