그리드패널에서 사용되는 스토어는 "Ext.data.Store" 를 사용하지만

트리패널에서 사용되는 스토어는 "Ext.data.TreeStore"를 사용합니다.


사용되는 데이터스토어가 다르고 스토어들의 사용법 또한 살짝(?) 다릅니다.


proxy 타입이 "memory" 기준으로 설명을 드리자면 



Ext.data.Store 데이터구조


1
2
3
4
5
6
7
8
9
data : [{
    blogger_id : 'guklife',
    blogger_name : '국이',
    blogger_url : 'guklife.tistory.com'
},{
    blogger_id : 'hellogk',
    blogger_name : '개발로짜',
    blogger_url : 'hellogk.tistory.com'
}]




위처럼 json array 하나에 여러개의 json object를 정의하는 구조인 1:n 형식입니다.

그렇다면 트리구조일 경우에는 데이터 출력을 위해 다음과 같은 구조로 정의해줍니다.




Ext.data.TreeStore 데이터 구조


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root : {
        text : '1depth',
        expanded : true,
        children: [{
            text:'2depth(1)',
            expanded: true,
            children:[{
                text:'3depth',
                leaf : true
            }]
        },{
            text:'2depth(2)',
            leaf : true
        }]
}




위 구조는 ajax 비동기 통신할때도 동일한 구조로 진행이 되어야 합니다.


각각 설명을 해보자면


① root속성부터 트리컴포넌트 1depth 노드의 시작이다. 

② 자식노드를 출력하기 위해서는 children 속성내에 json배열 형식으로 각 object 를 선언한다.

※ 속성에 알아봐야 할 중요 key 설명

  text : 트리구조 출력시 화면에 노출되는 문자열(필수)

  expanded : true/false boolean 형식의 값을 정의한다.

             true일 경우 - 자식노드 확장

             false일 경우 - 자식노드가 확장을 해놓지 않음

  leaf : 마지막 노드인지 구분을 위한 속성값

                  역시 true/false boolean 형태


  

  expanded 속성과 leaf 속성을 구분하여 다음의 case별로 적용해주시면 되실거 같습니다.

  

  1. 더이상의 자식노드가 없다면? expanded 속성 생략 + leaf : true

          이 경우 childrend 속성도 생략해야 하겠죠? 

  2. 자식노드가 존재하지만 확장을 시켜놓지 않을것이다? expanded : false

  3. 자식노드가 존재하며 확장을 시켜놓겟다? expanded : true

  

  위 3가지를 꼭 기억해주도록 합니다.



트리패널 샘플코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Ext.onReady(function(){
 Ext.onReady(function(){
   Ext.create('Ext.tree.Panel',{
        renderTo : Ext.getBody(),
        store : Ext.create('Ext.data.TreeStore',{
                    root : {
                        text : '1depth',
                        expanded : true,
                        children: [{
                            text:'2depth(1)',
                            expanded: true,
                            children:[{
                                text:'3depth',
                                leaf : true
                            }]
                        },{
                            text:'2depth(2)',
                            leaf : true
                        }]
                    },
                    proxy : {
                        type : 'memory'
                    }
                })
    })
});




위처럼 단순하게 트리컴포넌트를 생성해보았습니다.

실행결과를 확인해 보도록 합니다.







위처럼 트리구조로 목록이 출력되었습니다.


다음으로 proxy 타입이 'ajax'인 비동기방식으로 서버통신 후 

json 객체로 트리노드를 동적으로 출력해보도록 하겠습니다.


이번 json response 작업 역시 json-simple 라이브러리를 이용하여 진행하였습니다.



2014/10/06 - [코드저장소/java] - JSON 라이브러리를 이용하여 object생성과 문자열을 object형으로 변환해보기



상단 코드중 children 속성을 ajax call 하여 json object로 받을 예정입니다.

proxy 사용방법은 기존 그리드 ajax 와 동일한 구조입니다.

일부 변경된 스크립트 코드는 다음과 같습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Ext.onReady(function(){
   Ext.create('Ext.tree.Panel',{
        renderTo : Ext.getBody(),
        store : Ext.create('Ext.data.TreeStore',{
                    root : {
                        text : '1depth',
                        expanded : false
                    },
                    proxy : {
                        type : 'ajax',
                        api: {
                            read : '/tree_result.jsp'
                        },
                        reader: {
                            type: 'json',
                            rootProperty: 'children'
                        }
                    }
               })
    })
});




root 속성의 expanded 값을 false로 정의하였습니다.


트리패널에서는 서버통신이 이루어지는 경우는 

트리노드가 확장(expanded : true)이벤트가 발생할때 호출되기 때문에 

눈으로 확인해보고자 false로 지정하였습니다.


true로 줄경우 onload 되자마자 바로 트리패널의 children을 ajax call을합니다.


위와같이 작업하였다면 서버 페이지 코드를 작성해보도록 합니다.



서버페이지 json 코드(tree_result.jsp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
JSONObject jsonTreeRootObject = new JSONObject();
 
JSONArray jsonArray = new JSONArray();
JSONObject jsonTreeObject = null;
     
JSONArray jsonTreeChildrenArray = new JSONArray();
JSONObject jsonTreeChildrenObject = null;
     
jsonTreeObject = new JSONObject();
jsonTreeObject.put("text", "2depth(1)");
jsonTreeObject.put("leaf", true);
jsonArray.add(jsonTreeObject);
     
jsonTreeObject = new JSONObject();
jsonTreeObject.put("text", "2depth(2)");
jsonTreeObject.put("expanded", true);
     
jsonTreeChildrenObject = new JSONObject();
jsonTreeChildrenObject.put("text","3depth(1)");
jsonTreeChildrenObject.put("leaf",true);
jsonTreeChildrenArray.add(jsonTreeChildrenObject);
jsonTreeChildrenObject = new JSONObject();
jsonTreeChildrenObject.put("text","3depth(2)");
jsonTreeChildrenObject.put("leaf",true);
jsonTreeChildrenArray.add(jsonTreeChildrenObject);
     
jsonTreeObject.put("children",jsonTreeChildrenArray);
jsonArray.add(jsonTreeObject);
     
jsonTreeRootObject.put("success", true);
jsonTreeRootObject.put("children", jsonArray);
response.setContentType("text/plain; charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.print(jsonTreeRootObject);
pw.flush();
pw.close();



json 파싱코드가 기존 작업보다 상당히 길어지고 구조또한 복잡해진거 같죠?

트리의 json object는 depth 구조로 작업을 해야하기 때문입니다.


다음 구조를 보시면 이해가 되실겁니다.






추가 자식노드가 존재하는 json object에 children key값으로 

json array 객체를 담는구조가 되어야합니다.


실행을 해보도록 하겠습니다.







정상적으로 ajax call이 이루어지면서 json object 데이터를 화면에 출력이 되었습니다.


트리패널을 ajax call할때 depth별 구조를 잘 잡아 주어야 하므로 json 파싱작업때 주의해주세요!!



트리패널 ajax 호출 시 expand/collapse 이벤트가 한번만 발생하고 이후 동작이 되지 않을경우 

proxy속성의 동일 depth에  animate : false 속성을 추가해주도록 합니다.


by 개발로짜