Firebase Web 채팅앱 만들기 - 7. Realtime Database를 이용한 채팅기능 구현 - 유저리스팅 화면

7-1

1. 코드 작성

  • 아래와 같은 사용자 목록화면을 위한 코드 추가
    • 코드 설명 :
      • 로그인 인증이 완료되고 수행되는 setLogin메소드 안에서 Realtime Databse 에서 Users Reference를 불러오는 loadUserList 메소드가 수행.
      • oadUserList 메소드를 살펴보면 Users 위치를 once메소드를 통해 한번 만 불러오도록 되어 있고, userName 순으로 정렬하여 데이터를 가지고 옵니다.
      • off 메소드는 여러 메소드가 수행하는 과정에서 미리 할당된 이벤트가 있으면 이벤트를 제거한 후 다시 이벤트를 붙여서 중복으로 이벤트가 할당되는 것을 막기 위함.
      • getUserList 메소드는 데이터를 받고 최종적으로 화면을 그리는 코드가 수행.
      • getUserList 메소드안에 코드 수행 중에 _.template 구문이 있는데 이는 underscore.js 라이브러리의 template메소드.
      • once메소드를 통해 받은 데이터를 String 문자열로 붙이는 대신에 템플릿을 통한 코드 생성.
          /**
           * 초기 필드 변수 할당
           */
          FirebaseChat.prototype.init = function(){
              //...생략
              this.ulUserList = document.getElementById('ulUserList');
          }

          /**
           *  로그인 후 세팅
           */
          FirebaseChat.prototype.setLogin = function(user){  //user 파라미터 추
              //...생략
              this.loadUserList();
          }

          /**
           *  첫번째 탭 유저리스트 호출
           */
          FirebaseChat.prototype.loadUserList = function(){
              this.userTemplate = document.getElementById('templateUserList').innerHTML;
              var userRef = this.database.ref('Users');
              userRef.off();
              userRef.orderByChild("userName").once('value', this.getUserList.bind(this));
          }


          /**
           * loadUserList 에서 데이터를 받아 왔을 때
           */
          FirebaseChat.prototype.getUserList  =  function(snapshot) {
              var userListHtml = '';
              var cbDisplayUserList = function(data){
                  var val = data.val();
                  if(data.key !== this.auth.currentUser.uid){
                      userListHtml += _.template(this.userTemplate)({targetUserUid : data.key, profileImg : val.profileImg, userName : val.userName});
                  }
              }
              snapshot.forEach(cbDisplayUserList.bind(this));
              this.ulUserList.innerHTML = userListHtml;

          }
  • index.html파일 하단에 보면 script태그로 이루어진 아래의 코드가 있음
<!-- template 유저리스트 영역 -->
    <script type="text/template" id="templateUserList">
            <li id="li<%=targetUserUid %>" data-targetUserUid="<%=targetUserUid %>" data-username="<%=userName %>" class="collection-item avatar list">
                <img src="<%=profileImg ? profileImg : 'img/noprofile.png'  %>" alt="" class="circle">
                <span class="title"><%=userName %></span>
                <span class="small material-icons right hiddendiv done">done</span>
                <span class="small material-icons right hiddendiv mood yellow-text">mood</span>
            </li>
    </script>