Thursday, 20 April 2017

How to append buttons only for some users - socket.io

I've made a basic chat program, where users can create rooms to chat. When creating a room, two buttons are appended to the list of rooms: a join button, and a remove button. However, for users who did not create the room, the 'remove button' should NOT be displayed, since they cannot remove the room. Only Owners (user who created the room) can remove a room.

Vice versa, for owners of a room, the 'join button' should NOT be displayed, since they don't have to join it.

Below you can see an image of what the chat program looks like. The buttons I am refering to are located on the left side. enter image description here

The function that appends created room + the buttons, looks like this:

//Updating room list
    socket.on("roomList", function(data) {
      $("#rooms").text("");
      $("#rooms").append("<li class=\"list-group-item active\">List of rooms <span class=\"badge\">"+data.count+"</span></li>");

      if (!jQuery.isEmptyObject(data.rooms)) { 
        $.each(data.rooms, function(id, room) {
        var html = "<button id="+id+" class='joinRoomBtn btn btn-default btn-xs' >Join</button>" + " " + "<button id="+id+" class='removeRoomBtn btn btn-default btn-xs'>Remove</button>";
        $('#rooms').append("<li id="+id+" class=\"list-group-item\"><span>" + room.name + "</span> " + html + "</li>");
      });
      } else {
        $("#rooms").append("<li class=\"list-group-item\">There are no rooms.</li>");
        $("#msg").prop("readonly", true);
           $("#msg").attr("placeholder", "Join or create room to chat");
           $("#send").attr("disabled", true);
        }
    });



via JonasSH

No comments:

Post a Comment