var MyApp = MyApp || {};

MyApp.local = (function($) {

////////////////////////////////////////////////////////////////////////////////////////////////////

// start initialize

var  global            = this

    ,selectBaseUrl     = ""

    ,selectDivisionUrl = ""

    ,insertDivisionUrl = ""

    ,doDivsnSearch     = function() {

        var srch_site_nm = $("#srch_site_nm").val() || "";

         

        if ( srch_site_nm != "" ) {

            $("#divsnTree").dynatree("option","initAjax", {

                url         : selectDivisionUrl,

                dataType    : 'json',

                data        : {

                    mnu_id  : "ROOT",

                    site_id : srch_site_nm,

                    mode    : "all"

                }

            });

            $("#divsnTree").dynatree("getTree").reload();

        }

    }

    ;

// end initialize 

 

;$(document).ready(function() {

    // 베이스 트리 생성

    $("#baseTree").dynatree({

        title          : "",

        minExpandLevel : 1,

        initAjax       : {

            url        : selectBaseUrl,

            dataType   :'json',

            data       : {

            }

        },

        autoFocus      : true,

        onActivate     : function(node) {

        },

        onDeactivate   : function(node) {

        },

        onLazyRead: function(node) {

        },

        dnd            : {

            onDragStart: function(node) {

                /** This function MUST be defined to enable dragging for the tree.

                 *  Return false to cancel dragging of node.

                 */

                logMsg("tree.onDragStart(%o)", node);

                if ( node.data.isFolder ) {

                    return true;

                }

                return true;

            },

            onDragStop : function(node) {

                logMsg("tree.onDragStop(%o)", node);

            }

        }//dnd: {

    });//$("#baseTree").dynatree({

 

    // 부분별 과정 트리 생성

    $("#divsnTree").dynatree({

        title          : "",

        minExpandLevel : 1,

        autoFocus      : true, 

        initAjax       : {

            url        : selectDivisionUrl,

            dataType   :'json',

            data       : {

                mnu_id : "ROOT",

                site_id: $("#srch_site_nm").val(),

                mode   : "all"

            }

        },

        onPostInit     : function(isReloading, isError) {

            var initNode = this.getNodeByKey('TEMP');

            if (initNode) {

                var tempMsg = 'tempMsg';

                initNode.setTitle(tempMsg);

            }

            else {

                // 데이터가 있다면 펼쳐준다.

                $("#btn_divsnTreeExpandAll").click();

            }

            logMsg("onPostInit(%o, %o)", isReloading, isError);

            this.reactivate();

        },

        onActivate     : function(node) {

            $("#site_mnunm").val(node.data.title);

            $("#delete_divsn_key").val(node.data.key);

        },

        onDeactivate   : function(node) {

        },

        onLazyRead     : function(node){

            node.appendAjax({

                url      : selectDivisionUrl,

                dataType : "json",

                data     : {

                    mnu_id : node.data.key,

                    site_id: $("#srch_site_nm").val(),

                    mode   : "all"

                },

                cache    : false

            });

        },

        dnd           : {

            autoExpandMS    : 1000,

            preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.

            onDragStart: function(node) {

                /** This function MUST be defined to enable dragging for the tree.

                 *  Return false to cancel dragging of node.

                 */

                logMsg("tree.onDragStart(%o)", node);

                if ( node.data.isFolder ) {

                    return true;

                }

                return true;

            },

            onDragStop : function(node) {

                logMsg("tree.onDragStop(%o)", node);

            },

            onDragEnter     : function(node, sourceNode) {

                /** sourceNode may be null for non-dynatree droppables.

                 *  Return false to disallow dropping on node. In this case

                 *  onDragOver and onDragLeave are not called.

                 *  Return 'over', 'before, or 'after' to force a hitMode.

                 *  Any other return value will calc the hitMode from the cursor position.

                 */

                logMsg("tree.onDragEnter(%o, %o)", node, sourceNode);

                if ( node.data.isFolder ) {

                    return true;                    

                }

                return true;

            },

            onDragOver      : function(node, sourceNode, hitMode) {

              /** Return false to disallow dropping this node.

               *

               */

//               if(node.data.isFolder){

//                 var dd = $.ui.ddmanager.current;

//                 dd.cancel();

//                 alert("folder");

//               }

                logMsg("tree.onDragOver(%o, %o, %o)", node, sourceNode, hitMode);

            },

            onDrop          : function(node, sourceNode, hitMode, ui, draggable) {

                /**This function MUST be defined to enable dropping of items on the tree.

                 * sourceNode may be null, if it is a non-Dynatree droppable.

                 */

                logMsg("tree.onDrop(%o, %o)", node, sourceNode);

                var  copynode    = null

                    ,isSelf      = false

                    ;

                if (sourceNode) {

                    isSelf = (node.tree==sourceNode.tree);

                    // 키 중복 확인

                    try {

                        if ( isSelf == false ) {

                            node.tree.getRoot().visit(function(node){

                                if ( node.data.key == sourceNode.data.key ) {

                                    throw {message : "항목이 중복됩니다."};

                                }

                            });                         

                        }

                    }

                    catch(e) {

                        alert(e.message);

                        return;

                    }

                    finally  {}

                     

                    var temp_node = node.tree.getNodeByKey("TEMP");                    

                    var copy_node = node;

                    var myParent  = null;

                    var isTemp    = false;

                     

                    // 처음 생성시일때만 체크 : 처음생성시에는 TEMP 노드 밑에 들어가 있어야 한다.

                    if ( temp_node != null ) {

                        if ( hitMode == "over") {

                            if ( node.data.key == "TEMP" ) {

                                isTemp = true;

                            }

                        }

                             

                        while ( (myParent = copy_node.getParent()) != null ) {

                            if ( myParent.data.key == "TEMP" ) {

                                isTemp = true;

                            }

                            copy_node = myParent;

                        }

                         

                        if (temp_node != null && isTemp == false) {

                            var tempMsg = 'tempMsg';

                            alert(tempMsg);

                            return;

                        }                           

                    }

 

                    // 다른 트리에서 Drag N Drop을 할때  : 복사하고 넣어준다.

                    if ( isSelf == false ) {

                        copynode = sourceNode.toDict(true, function(dict) {

                            dict.title = "[*] " + dict.title;                           

                            // 2012.02.09 GDJ : 위 로직에서 키 중복체크를 하기 때문에 그데로 사용해도 문제 없다.

                            //delete dict.key; // Remove key, so a new one will be created

                        });                     

                         

                        if (hitMode == "over") {

                            // Append as child node

                            node.addChild(copynode);

                            // expand the drop target

                            node.expand(true);

                             

                            // 폴더로 변경해주고 다시 그려준다.

                            node.data.isFolder = true;

                            node.tree.redraw();

                        }

                        else if (hitMode == "before") {

                            // Add before this, i.e. as child of current parent

                            node.parent.addChild(copynode, node);

                        }

                        else if (hitMode == "after") {

                            // Add after this, i.e. as child of current parent

                            node.parent.addChild(copynode, node.getNextSibling());

                        }

                    }

                    // 자기 트리에서는 이동시킨다.

                    else {

                        (function() {

                            // 부모가 수정되었다고 알려준다.

                            var parent = sourceNode.getParent();

                            if ( parent != null && parent.data.key != "ROOT" ) {

                                var title  = parent.data.title;

                                if ( title != null ) {

                                    title = "[*] " + title.replace(/^(\[\*\]\s)?(.+)$/mi, "$2");

                                    parent.data.title = title;                                  

                                }

                            }

                        })();

 

                        sourceNode.move(node, hitMode);

                        if ( hitMode == "over") {

                            node.expand(true);

                            (function() {

                                // 부모가 수정되었다고 알려준다.

                                var parent = node;

                                if ( parent != null && parent.data.key != "ROOT" ) {

                                    var title  = parent.data.title;

                                    if ( title != null ) {

                                        title = "[*] " + title.replace(/^(\[\*\]\s)?(.+)$/mi, "$2");

                                        parent.data.title = title;                                  

                                    }

                                }

                            })();

                        }

                        node.tree.getRoot().visit(function(callback_node){

                            var myNode = callback_node;

                            myNode.data.isFolder = (myNode.getChildren()==null ? false:true);

                        });

                     

                        node.tree.redraw();                         

                        return;

                    }

                } 

                else {

                    copynode = {title: "This node was dropped here (" + ui.helper + ")."};

                    alert(copynode.title);

                }

            },//onDrop          : function(node, sourceNode, hitMode, ui, draggable) {

            onDragLeave     : function(node, sourceNode) {

                /** Always called if onDragEnter was called.

                 */

                 logMsg("tree.onDragLeave(%o, %o)", node, sourceNode);

            }

        }//dnd: {

    });//$("#divsnTree").dynatree({

 

    // 부분별 셀렉트 박스

    $("#srch_site_nm").change(function() {

        doDivsnSearch();

    });

     

    // 검색

    $("#btn_search").click(function() {

        doDivsnSearch();

    }); 

     

    // 베이스 트리 모두 펼치기

    $("#btn_baseTreeExpandAll").click(function() {

        $("#baseTree").dynatree("getRoot").visit(function(node){

            node.expand(true);

        });

    });   

     

    // 베이스 트리 모두 접기

    $("#btn_baseTreeCollapseAll").click(function() {

        $("#baseTree").dynatree("getRoot").visit(function(node){

            node.expand(false);

        });

    });

  

    // 부분별 과정 트리 모두 펼치기

    $("#btn_divsnTreeExpandAll").click(function() {

        $("#divsnTree").dynatree("getRoot").visit(function(node){

            node.expand(true);

        });

    });

     

    // 부분별 과정 트리 모두 접기

    $("#btn_divsnTreeCollapseAll").click(function() {

        $("#divsnTree").dynatree("getRoot").visit(function(node){

            node.expand(false);

        });

    });

     

    // 부분별 과정 저장

    $("#btn_divsnSave").click(function() {

        var  $tree = $("#divsnTree")

            ,data  = []

            ;

        var srch_site_nm = $("#srch_site_nm").val();

        if ( srch_site_nm == "" ) {

            alert("부분을 선택하세요.");

            return;

        }

         

        $tree.dynatree("getRoot").visit(function(node) {

            var  item     = {}

                ,myParent = node.getParent()

                ,title    = node.data.title  || ""

                ,key      = node.data.key    || "" 

                ;

             

            item.subjclass   = key;

            // 신규 저장일때의 [*] 을 제거한다.

            item.classnm = title.replace(/^(\[\*\] )?(.+)$/gmi, "$2");

            if ( myParent == null ) {

                item.upsubjclass  = "";

                item.orders = 1;

            }

            else {

                if ( myParent.data.key == "TEMP" || myParent.data.key == "_1") {

                    item.upsubjclass   = "ROOT";                    

                }

                else {

                    item.upsubjclass   = myParent.data.key;

                }

 

                var order   = 1;

                var preNode = node;

                while ( (preNode=preNode.getPrevSibling()) != null ) {

                    order++;

                }

                item.orders  = order;

            }

            item.site_id = srch_site_nm;

             

            if ( item.subjclass.toUpperCase() != "TEMP" ) {

                data.push(item);                

            }

        });

         

        // Root 데이터를 맨앞에 넣어준다.

        var rootData = [];

        rootData.push({

             site_id     : srch_site_nm

            ,classnm     : "ROOT"

            ,subjclass   : "ROOT"

            ,upsubjclass : ""

            ,orders      : 1

        });

        data = rootData.concat(data);

         

        // 통신

        $.ajax({

            url          : insertDivisionUrl,

            type         : 'POST',

            dataType     : 'json',

            contentType  : 'application/json; charset=utf-8', 

            data         : JSON.stringify({

                site_id  : srch_site_nm,

                data     : data

            }),

            success  : function(result) {

                alert(result.message);

                if ( result.success == true ) {

                    doDivsnSearch();

                }

            },

            error    : function(result) {

            }

        });//$.ajax({

    });

     

    // 부분별 과정 삭제

    $("#btn_divsnDelete").click(function() {

        var  k     = $("#delete_divsn_key").val()

            ,$tree = $("#divsnTree").dynatree("getTree")

            ,node  = $tree.getNodeByKey(k)

            ;

        // TEMP노드는 삭제하지 않는다.

        if ( k == "TEMP" ) {

            return;

        }

         

        if ( node != null ) {

            var parent = node.getParent();

            if ( parent != null && parent.data.key != "ROOT" ) {

                var title  = parent.data.title;

                if ( title != null ) {

                    title = "[*] " + title.replace(/^(\[\*\]\s)?(.+)$/mi, "$2");

                    parent.data.title = title;                  

                }

            }

 

            node.remove();

            $("#site_mnunm").val("");

            $tree.redraw();

        }

        else {

            alert("null");

        }

    });

     

    // test

    (function() {

    })();

});//$(document).ready(function() {

     

// 외부에 오픈할 인터페이스

return {

};

////////////////////////////////////////////////////////////////////////////////////////////////////

})(jQuery);

 


'JavaScript > dynaTree' 카테고리의 다른 글

[dynatree] dynatree node option  (0) 2012.02.09
[dynatree] Option 옵션  (0) 2012.02.09
[dynatree] dynatree (jQuery 기반의 tree-plugin)  (0) 2012.02.08
posted by 뚱2

티스토리를 사용하면서 다양한 스킨과 플러그인... 참 좋은데 다만 하나!!
이넘의 카테고리를 트리구조로 선택하면... 페이지를 클릭할때마다 내가
펼쳤던 카테고리가 닫히는 문제가 발생하네요... ㅡㅡ;

이랬던 페이지가 링크를 클릭하거나
새로고침을 하면은....















이렇게 되버리는 아주 XX 같은 경우










기능상의 한계인가보다 생각하고 카테고리를 트리구조로 만들지 않고 평범하게
1 Level로 사용했었습니다.
그런데 여기 저기 방문하다 보니 어느분의 티스토리는 분명.. 펼쳐저 있는겁니다.
그래서 다시 한번 옵션을 찾아봤지만 안보이네요... ㅡㅡ;
그렇지만 남이되면 나도 안될 이유는 없기에 욜심히 찾아봤습니다.
그래서 찾아낸것은 쉽게 옵션으로 조정은 안되구요

1. Admin에 들어와서 'HTML/CSS 편집' 에
들어갑니다.












2. 위와 같이 <body> 태그에 'OnLoad="expandTree();"' 이벤트를 넣어주심 됩니다.


3. 다른방법으로는 jQuery 를 이용해서 할 수도 있습니다.
* jQuery $(window).load 이벤트가 IE8에서 오류가 나서 수정
//jQuery.noConflict();
(function($) {
    var that = this;
    that.doLoad = function() {
        expandTree();
    };

    $(document).ready(function() {
        SyntaxHighlighter.config.bloggerMode = true;
        //SyntaxHighlighter.defaults['html-script'] = true;
        SyntaxHighlighter.all();

        if ( window.addEventListener ) { 
            window.addEventListener( "load", that.doLoad, false );
        }
        else if ( window.attachEvent ) { 
            window.attachEvent( "onload", that.doLoad );
        } 
        else if ( window.onLoad ) {
            window.onload = that.doLoad;
        }
    });//$(document).ready(function() {
})(jQuery);


'뚱2's 이야기' 카테고리의 다른 글

조이스틱을 개조해 보자  (0) 2009.03.04
T61P 14.1 UXGA  (2) 2009.02.28
최근에 사용한 문서 지우기  (0) 2008.09.12
Takata04-neo  (0) 2008.08.17
Sony HANDYCAM HDR-TG1  (0) 2008.07.19
posted by 뚱2