当前访客身份:游客 [ 登录 | 加入开源中国 ]

代码分享

当前位置:
代码分享 » JavaScript  » Web编程
分享到: 
收藏 +0
0
nodejs平台的组织结构图,增删改一键保存,减少与db的交互
标签: <无>

代码片段(2) [全屏查看所有代码]

1. [文件] jquery.catChart.js ~ 12KB     下载(53)     跳至 [1] [2] [全屏预览]

//state:编辑状态码:0为未操作,1新增,2新增,3删除
var json = [];
var nodes = [];

(function($) {

    var defaults = {
        depth      : -1,
        chartClass : "jOrgChart",
        dragAndDrop: true,
        rootId : 0,
        addNodeUrl : "",
        removeNodeUrl : "",
        updateNodeUrl : ""
    };

    var data , option , $this;

    //初始化
    $.fn.jOrgChart = function(d,options) {
        $this = $(this);
        option = $.extend({}, defaults, options);
        $this.addClass(option.chartClass);
        data = d;
        render();
        initEvent();
        return $this;
    };

    //生成父节点
    function render(){
        $this.html('');
        var $rootNode = findNode(option.rootId);
        buildNode($rootNode ,$this , 0 , option);
        bindDrag();
    }

    function bindDrag(){
        $('div.node').draggable({
            cursor      : 'move',
            distance    : 40,
            helper      : 'clone',
            opacity     : 0.8,
            revert      : 'invalid',
            connectToSortable: "#" + $this.attr("id"),
            revertDuration : 100,
            snap        : 'div.node.expanded',
            snapMode    : 'inner',
            stack       : 'div.node'
        });

        $('div.node').droppable({
            accept      : '.node',
            activeClass : 'drag-active',
            hoverClass  : 'drop-hover'
        });


        $('div.node').bind("drop",function(event, ui){
            var targetID = $(this).attr("nodeId");
            var sourceID = ui.draggable.attr("nodeId");

            var node = findNode(sourceID);
            node.pid = targetID;
        });

        $('div.node').bind("dragstart",function handleDragStart( event, ui ){

            var sourceNode = $(this);
            sourceNode.parentsUntil('.node-container')
                .find('*')
                .filter('.node')
                .droppable('disable');
        });

        $('div.node').bind("dragstop", function handleDragStop( event, ui ){

            /* reload the plugin */
            render();
        });

    }

    //添加子节点
    function initEvent(){
        $this.delegate("input[type=button][addNode]","click",function(){
            var id = $(this).attr("addNode");
            addNode({pid : id , name : "节点名称"});
            //此id为新节点的 父节点的id
        })

        $this.delegate("input[type=button][removeNode]","click",function(){
            if(confirm("是否需要删除?")){
                var id = $(this).attr("removeNode");

                //将要删除的节点让如json中
                //json.push({id:id,state:3});
                /*var arr = findChildNodes(id);
                for(var i=0;i<arr.length;i++){
                    var cid = arr[i].id;
                    json.push({id:cid,state:3});
                }*/

                findAllChild(id);
                for(var i=0;i<nodes.length;i++){
                    json.push({id:nodes[i].id,state:3});
                }
                removeNode({id:id});


            }
        })

        $this.delegate("input[type=button][updateNode]","click",function(){
            var id = $(this).attr("updateNode");
            var span = $(this).parents(".node").find("span").hide();
            var input = $(this).parents(".node").find("input[type=text]");

            //获取该节点
            var d = findNode(id);
            var pid = d.pid;
            if(input[0]){
                input.show();
            }else{
                input = $('<input type="text" value="'+span.text()+'">');
                input.focus(function(){
                    $(this).select();
                });
                input.blur(function(){
                    span.text(input.val()).show();
                    input.hide();
                    updateNode({id : id , name : span.text()});
                    if(d.state == 1){
                        $.each(jsonData,function(i,n){
                            if(n.id == d.id){
                                n.name = span.text();
                            }
                        })
                    }else{
                        $.each(jsonData,function(i,n){
                            if(n.id == d.id){
                                n.name = span.text();
                                n.state = 2;
                            }
                        });

                    }
                    input = null;
                })
                span.after(input);
            }

        })

        if(option.dragAndDrop){
            bindDrag($('div.node'));
        } // Drag and drop
    }

    function findNode( id  ){
        var d;
        $.each(jsonData,function(i,n){
            if(n.id == id){
                d = n;
                return false;
            }
        });
        return d;
    }

    function findChildNodes( id ){
        var ds = [];
        $.each(data,function(i,n){
            if(n.pid == id){
                ds.push(n)
            }
        });
        return $(ds);
    }


    function buildNode($node, $jqEle, level, opts ){
        var $table = $("<table cellpadding='0' cellspacing='0' border='0'/>");
        var $tbody = $("<tbody/>");

        // Construct the node container(s)
        var $nodeRow = $("<tr/>").addClass("node-cells");
        var $nodeCell = $("<td/>").addClass("node-cell").attr("colspan", 2);


        var $childNodes = findChildNodes( $node.id , data);

        var $nodeDiv;

        if($childNodes.length > 1) {
            $nodeCell.attr("colspan", $childNodes.length * 2);
        }

        //Increaments the node count which is used to link the source list and the org chart


        $nodeDiv = $("<div>").addClass("node").attr("nodeId" , $node.id)
            .append('<span url="'+$node.url+'">'+$node.name+'</span>')
            .append($('<div class="inputGroup"><input type="button" addNode="'+$node.id+'" value="+" ><input type="button" updateNode="'+$node.id+'" value="编辑"><input type="button" removeNode="'+$node.id+'" value="-"></div>'));

        $nodeCell.append($nodeDiv);
        $nodeRow.append($nodeCell);
        $tbody.append($nodeRow);

        if($childNodes.length > 0) {
            // if it can be expanded then change the cursor
            $nodeDiv.css('cursor','n-resize');

            // recurse until leaves found (-1) or to the level specified
            if(opts.depth == -1 || (level+1 < opts.depth)) {
                var $downLineRow = $("<tr/>");
                var $downLineCell = $("<td/>").attr("colspan", $childNodes.length*2);
                $downLineRow.append($downLineCell);

                // draw the connecting line from the parent node to the horizontal line
                $downLine = $("<div></div>").addClass("line down");
                $downLineCell.append($downLine);
                $tbody.append($downLineRow);

                // Draw the horizontal lines
                var $linesRow = $("<tr/>");
                $childNodes.each(function() {
                    var $left = $("<td>&nbsp;</td>").addClass("line left top");
                    var $right = $("<td>&nbsp;</td>").addClass("line right top");
                    $linesRow.append($left).append($right);
                });

                // horizontal line shouldn't extend beyond the first and last child branches
                $linesRow.find("td:first")
                    .removeClass("top")
                    .end()
                    .find("td:last")
                    .removeClass("top");

                $tbody.append($linesRow);
                var $childNodesRow = $("<tr/>");
                $childNodes.each(function() {
                    var $td = $("<td class='node-container'/>");
                    $td.attr("colspan", 2);
                    // recurse through children lists and items

                    buildNode(this, $td, level+1, opts);
                    $childNodesRow.append($td);
                });

            }
            $tbody.append($childNodesRow);
        }

        $table.append($tbody);
        $jqEle.append($table);

        $nodeDiv.children('a').click(function(e){
            e.stopPropagation();
        });
    }

    function addNode(node){
//        $.getJSON(option.addNodeUrl,{pid : node.pid},function(data){
//            data.push(data);
//            render();
//        })
        //var j = {id:Math.floor(Math.random()*90 + 10) , pid : node.pid ,name : node.name , url : "",state:1}
        //var id = uuid();
        //console.log("id:"+id);
        //var j = {id:id, pid : node.pid ,name : node.name , url : "",state:1}
        var id = Math.floor(Math.random()*90000 + 10);
        for (var i in jsonData){
            while(id == i.id){
                id = Math.floor(Math.random()*90000 + 10);
            }
        }
        var j = {id:id , pid : node.pid ,name : node.name , url : "",state:1}
        data.push(j);
        render();
    }

    function removeNode(node){
//        $.getJSON(option.removeNodeUrl,{id : node.id},function(d){
//            $.each(data,function(i,n){
//                if(n.id == d.id){
//                    data.splice(i , 1);
//                    return false;
//                }
//            })
//            render();
//        })
        $.each(jsonData,function(i,n){
            if(n.id == node.id){
                data.splice(i , 1);
                return false;
            }
        })
        render();
    }

    function updateNode(node){
//        $.getJSON(option.updateNodeUrl,{id : node.id , pid : node.pid , name : node.name , url : node.url},function(d){
//            $.each(data,function(i,n){
//                if(n.id == d.id){
//                    data.splice(i , 1 , d);
//                    return false;
//                }
//            })
//            render();
//        })

        $.each(jsonData,function(i,n){
            if(n.id == node.id){
                node.pid = n.pid;
                node.state = n.state;
                data.splice(i , 1 , node);
                return false;
            }
        })
        render();

    }

    function findAllChild(id){
        nodes.push(findNode(id));
        var c = findChildNodes(id);
        for(var i=0;i<c.length;i++){
            findAllChild(c[i].id);
        }
    }

})(jQuery)

//保存重置按钮
$(document).ready(function(){
     $('#JSqueryBtn').click(function () {

         var jsonParam = {opt:'wms550',param:{chaData:jsonData,delData:json}};
         var jsonState = JsonGetData(jsonParam,"/entryway","json");

         if(jsonState.status==1){
            alert("保存成功!");
             var jsonParam = {opt:'wms449',param:{tbName:"cctest",tdName:["id","pid","name","state"]}}

             var jsonData2 =JsonGetData(jsonParam ,"/entryway","json");
             if(jsonData2.status==1){
                 jsonData = jsonData2.jsonData;
                 console.log(jsonData);
                 window.location.reload();
             }else{y
                 prolog.base.MessageBox(jsonData2.errorCode);
             }
         }else{
             alert("保存失败!");
         }
         /*alert(JSON.stringify(json));
         alert(JSON.stringify(jsonData));*/
     });

    $('#ResetBtn').click(function (){
        window.location.reload();
    });
 });

//生成uuid
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

2. [代码][JavaScript]代码     跳至 [1] [2] [全屏预览]

<script>
              var jsonParam = {opt:'wms449',param:{tbName:"cctest",tdName:["id","pid","name","state"]}}
              var jsonData =JsonGetData(jsonParam ,"/entryway","json");
              if(jsonData.status==1){
                jsonData = jsonData.jsonData;
              }else{
                prolog.base.MessageBox(json.errorCode);
              }
              //当页面加载时,获取显示的div,将数据传入即可
              jQuery(document).ready(function() {
                $("#org2").jOrgChart(jsonData);
              });
            </script>

            <div id="queryBtn">
              <input type="button" id="JSqueryBtn" value="保存">
              <input type="button" id="ResetBtn" value="重置">
            </div>

            <div id="org2" ></div>


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

开源从代码分享开始 分享代码
小草先森的其它代码 全部(1)...