링크 : http://firejune.com/1275/자바스크립트+메모리+릭+디텍터?stag=메모리+릭 

링크 : http://rhio.tistory.com/177



JSLeaksDetector.msi


posted by 뚱2

tistory syntaxhighlighter 설정

일반 2012. 7. 26. 12:51

참고 : 다른 분것 참조를 했는데 링크를 읽어버렸습니다. ㅡㅡ;


위에 링크를 참조해서 span 태그의 whitepace 문제 수정


<script type="text/javascript">

<!--

;jQuery.noConflict();  // 다른 라이브러리와 충돌을 방지한다.

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

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

    $("blockquote[class^=brush]").each( function() {  //blokquote를 사용한 태그

        var $this = $(this);


// 복사 붙여넣기 했을때 탭처리

        $this.find("span[class*=Apple-tab-span]").replaceWith(function() {

            return $(this).text();

        });


// 편집창에서 직접 수정했을때 탭 처리

        $this.find("p[style*=margin-left]").each(function() {

            var $elem = $(this);

            var style = $elem.attr("style");

            var result = /\s*?margin-left:\s(\w+?)em;\s*?/gi.exec(style);

            if ( result != null ) {

                result = result[1];

            }

            var spaceCount = parseInt(result) * 2;

            var spaceString = "";

            for (var i = 0; i < spaceCount; i++) {

                spaceString += "&nbsp;";

            }

            $elem.removeAttr("style");

            $elem.html(spaceString + $elem.html());

        });


        var temp = $this.html(); //  내용 복사

        temp = temp.replace(/\n/gi, "");

        temp = temp.replace(/<p><\/p>/gi, "");

        temp = temp.replace(/<p><br\s*\/?><\/p>/gi, "\n");    // 줄바꿈

        temp = temp.replace(/<P>(.*?)<\/P>/gi, "$1\n");       // 한줄끝

        temp = temp.replace(/<br\s*\/?>/gi, "\n");            // 줄바꿈


        temp = '<script type="syntaxhighlighter" class="' + $this.attr('class') + '"><![CDATA[' + temp + ']]><\/script>'

        $this.replaceWith(temp);

    });

  

    $("pre[class^=brush]").each( function() {  //pre를 사용한 태그

var $this = $(this);

        var temp = $this.html(); //  내용 복사

        temp = temp.replace(/</g, "&lt;");

        $this.html = temp;

    });     


    /*  SyntaxHighlighter 사용부분  */

    SyntaxHighlighter.defaults['toolbar'] = false; // 툴바 안 보기

    SyntaxHighlighter.all();

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

});})(jQuery);

//-->

</script>


posted by 뚱2
자바의 import와 비슷하게 패키지 명을 입력해서 인클루드 하게 만들었습니다.

/**

* url은 문자열 배열이나 문자열이 올수 있다.

* 예) "SEED.df.DF_01.DF_HEADER_SEL"

*     ["SEED.df.DF_01.DF_HEADER_SEL", "SEED.df.DF_01.DF_HEADER"]

*/

SEED.importScript = function(url) {

var urls = [];

if ( url == undefined || url == null || url == "" ) {

return;

}

if ( $.type(url) == "string" ) {

urls.push(url);

}

else if ( $.type(url) == "array" ) {

urls = url;

}

else {

return;

}

$.each(urls, function(index, el) {

var newUrl = el.replace(/(^SEED\.)/gi, ""); // SEED가 있다면 제거한다. 

newUrl = newUrl.replace(/\./g, "/") + ".js";

var fullUrl = SEED.contextPath.get() + "/resources/js/" + newUrl;

$script = $("<script type=\"text/javascript\" charset=\"utf-8\" src=\"" + fullUrl + "\"></script>");

$script.bind("readystatechange", function() {

var $this = $(this);

if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

// FIXME : 나중에 메모리가 세는지 꼭 검사해야 한다.

// Handle memory leak in IE

this.onload = this.onreadystatechange = null;

$this.remove();

}

});

$script.appendTo("body");

});

};


posted by 뚱2

한글주소를 URL뒤에 붙이는 쿼리 스트링으로 전달하면 깨지는 경우가 발생합니다.

이럴때는 인코딩을 해줘야 합니다.



참고 : http://www.w3schools.com/jsref/jsref_obj_global.asp


위에서


FunctionDescription
decodeURI()Decodes a URI
decodeURIComponent()Decodes a URI component
encodeURI()Encodes a URI
encodeURIComponent()Encodes a URI component
escape()Encodes a string


함수를 이용하시면 됩니다.

posted by 뚱2

[jQuery] ajaxForm 구현

JavaScript/jQuery 2012. 7. 23. 00:31

사실 ajax를 이용하는게 아니라 예전부터 많이 사용하던 iframe을 이용하여 화면 깜빡임을 없애는 방식이다.


/**

 * form을 ajax로 전송한다. (파일 포함)

 */

$.fn.ajaxForm = function(handler) {

    var $this = $(this);

    if ( $this[0] && $this[0].tagName.toUpperCase() == "FORM" ) {

        //랜덤한 수를 출력

        var ranNumber = Math.floor(Math.random() * 10000) + 1;

        var strId = "";

        strId += "SEED";

        strId += "_";    

        strId += (new Date()).getTime();

        strId += "_" + ranNumber;


        $this.attr("target", strId);    

        $("<iframe id=\"" + strId + "\" name=\"" + strId + "\" />")

            .hide()

            .appendTo($this.parents("body"))

            .load(function() {

                var that = this;


                if ( $.type(handler) == "function" ) {

                    var result = $.parseJSON(window.frames[strId].document.body.innerHTML);

                    if ( result == undefined || result == null || result == "" ) {

                        result = {

                            success : false,

                            message : "결과가 존재하지 않습니다."

                        };

                    }

                    handler(result);

                }

            });

    }//if ( $this[0] && $this[0].tagName.toUpperCase() == "FORM" ) {


    return $this;

};


사용방법

(function($, exports) {$(document).ready(function() {

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

$("#myform").ajaxForm(function(result) {

    if ( result && result.success == true ) {

        alert(result.message);

    }

});

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

});})(jQuery, window);



참고 : http://hanjiq.egloos.com/2373084 

posted by 뚱2

자바스크립트는 선언되지 않는 변수에 값을 할당하면은 자동적으로 글로벌에 생성됩니다.

 

다만 선언되지 않은 변수를 사용하면 런타임에러가 발생합니다.

 

그리고 정의 되었지만 값을 할당한 적이 없는 경우는 undefined가 리턴됩니다.

 

또한 객체의 정의되지 않는 property를 읽을때도 undefined가 리턴됩니다.

 

참고 : 자바스크립트 완벽 가이드

// 현재 값은 undefined
var no_init; 
// 선언되지 않은 변수를 사용했기 때문에 에러가 발생
alert(u); 
//선언되지 않은 변수에 값을 할당하려 하는 순간 이 변수가 생성된다.
u = 3;

posted by 뚱2

[Javascript] DateAdd

JavaScript/JavaScript 2012. 7. 14. 22:22
// 예 add_DATEs("2012-12-31", 3) 이면 2013-01-03을 리턴
function add_DATEs(dateformat, dates) {
	dateformat = clear_DateSTRING(dateformat);
	var int_millisecond = 1;
	var int_second      = 1000 * int_millisecond;
	var int_minute      = 60 * int_second;
	var int_hour        = 60 * int_minute;
	var int_day         = 24 * int_hour;
	
	var YY_form = CInt(Left(dateformat, 4));
	var MM_form = CInt(Mid(dateformat, 5, 2))-1;
	var DD_form = CInt(Right(dateformat, 2));
	
	var date = new Date(YY_form, MM_form, DD_form);
	var date_milliseconds = date.valueOf();
	var add_milliseconds  = dates * int_day;
	var ret_date = new Date(date_milliseconds + add_milliseconds);
	
	var year  = ret_date.getFullYear();
	var month = ret_date.getMonth() + 1;
	if ( month < 10 ) {
		month = "0" + month;
	}
	var day   = ret_date.getDate();
	if ( day < 10 ) {
		day = "0" + day;
	}
	
	return ( "" + year + month + day );
}
posted by 뚱2

참고 : http://codemuri.tistory.com/756 

자바스크립트는 기본적으로 탐욕적 수량자이다.


1. 탐욕적 수량자와 게으른 수량자


 탐욕적 수량자게으른 수량자 
 * *? 
 + +? 
 {n,} {n,}? 

posted by 뚱2

참조 : JavaScript Patterns 에서 발췌


//=======================================================================
// SEED Class 영역
//=======================================================================
var SEED = SEED || {};

/**
 * 네임스페이스를 생성한다.
 * @param ns_string
 */
SEED.ns = function(ns_string) {
	var parts = ns_string.split("."),
		parent = SEED,
		i;
	
	// 처음에 중복되는 전역 객체명은 제거한다.
	if ( parts[0] === "SEED" ) {
		parts = parts.slice(1);
	}
	
	for (i = 0; i < parts.length; i++) {
		// 프로퍼티가 존재하지 않는다면 생성한다.
		if ( typeof parent[parts[i]] === "undefined" ) {
			parent[parts[i]] = {};
		}
		
		// 자식들을 검사하기 위해서 현재 나를 부모로 만든다.
 		parent = parent[parts[i]];
	}
	
	return parent;
};

// 사용예
var module2 = SEED.ns("SEED.modules.modules2");
module2 === SEED.modules.module2;//true

posted by 뚱2



posted by 뚱2

/**

 * obj  : url or json data

 * data : json data

 */

my.submitWithJson = function(obj, data, target, method) {

    try {

        var param = null;       

        // json object이라면

        if ( obj && Object.prototype.toString.call(obj) === '[object Object]' ) {

            param = {

                 'url'     : obj.url                 || ''

                ,'data'    : obj.data                || {}

                ,'target'  : obj.target              || '_self'

                ,'method'  : obj.method              || 'POST'

            };

        }

        else {

            param = {

                 'url'     : obj                     || ''

                ,'data'    : data                    || {}

                ,'target'  : target                  || '_self'

                ,'method'  : method                  || 'POST'

            }; 

        }

         

        //랜덤한 수를 출력

        var curDate   = new Date();

        var ranNumber = Math.floor(Math.random() * 10000) + 1;

        var strId = "";

            strId += param.target;

            strId += "_";           

            strId += curDate.getFullYear();

            strId += curDate.getMonth();

            strId += curDate.getDay();

            strId += curDate.getHours();

            strId += curDate.getMinutes();

            strId += curDate.getSeconds();

            strId += "_" + ranNumber;

             

        var $newForm = jQuery("<form></form>")

                        .attr("name"  , strId)

                        .attr("id"    , strId)

                        .attr("method", param.method);

        if ( $newForm ) {

            if ( Object.prototype.toString.call(param.data) === "[object Array]") {

                jQuery.each(param.data, function(index, val) {

                    var row = val;

                    jQuery.each(row, function(key, val) { 

                        jQuery("<input type='"hidden"'>")

                            .attr("name" , key)

                            .attr("value", val)

                            .appendTo($newForm);

                    });

                });

                $newForm.appendTo(document.body);

            }

            else {

                jQuery.each(param.data, function(key, val) { 

                    jQuery("<input type='"hidden"'>")

                        .attr("name" , key)

                        .attr("id"   , key)

                        .attr("value", val)

                        .appendTo($newForm);

                });

                $newForm.appendTo(document.body);               

            }

     

            var myForm = $newForm[0];

            myForm.action = param.url;

            myForm.method = param.method;

            myForm.target = param.target;

             

            myForm.submit();

            $newForm.remove();

        }//if ( $popForm ) {

    }

    catch (e) {alert(e.message);}

    finally   {}

}; 


posted by 뚱2

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
원본 : http://koko8829.tistory.com/1155

Dojo는 꽤 오랜 역사(2004년부터)를 가지고 있음에도 불구하고 국내에서는 잘 알려지지 않은 프레임워크입니다. 이름때문에 그런지도 모르겠네요.
IBM에서 적극적으로 참여하고 있기 때문에 얼마전 DW에 대량으로 기술자료가 공개가 되었습니다.

우선 가장 기본적인 시작하기 부터
Dojo 처음부터 시작하기, Part 1: Dojo 개발 시작하기
http://www.ibm.com/developerworks/kr/library/wa-ground/  

http://pragprog.com/book/rgdojo/mastering-dojo

http://pragprog.com/book/rgdojo/mastering-dojo


자바스크립트에 대한 경험이 없는 자바개발자들을 위한 콘텐츠도 제공하고
Java 개발자를 위한 Dojo 개념
http://www.ibm.com/developerworks/kr/library/wa-aj-dojo/index.html  

대규모 애플리케이션 개발에 이르기까지 다양한 주제를 다루고 있습니다.
사용자 정의 Dojo 빌드로 대규모 웹 애플리케이션을 신속하게 로드하기
http://www.ibm.com/developerworks/kr/library/wa-bigweb/index.html  

12월에 올라온 자료만 10건이 넘네요. 
http://www.ibm.com/developerworks/kr/views/web/libraryview.jsp  

자신에게 맞는 콘텐츠를 골라서 개념적인 접근을 할 수 있습니다.
좀 더 기본적인 내용은  http://dojofoundation.org/ 에서 참고할 수 있습니다.

* dojo (どうじょう)는 일본어로 도장이라는 의미입니다. 개발을 수련의 과정으로 이미지화하면서 이런 이름을 가지게 된것이 아닌가 싶네요. 위에 있는 책 표지부터 그런 느낌이 나죠.
posted by 뚱2
children: [
    {
    title: null, // (required) Displayed name of the node (html is allowed here)
    key: null, // May be used with activate(), select(), find(), ...
    isFolder: false, // Use a folder icon. Also the node is expandable but not selectable.
    isLazy: false, // Call onLazyRead(), when the node is expanded for the first time to allow for delayed creation of children.
    tooltip: null, // Show this popup text.
    href: null, // Added to the generated < a > tag.
    icon: null, // Use a custom image (filename relative to tree.options.imagePath). 'null' for default icon, 'false' for no icon.
    addClass: null, // Class name added to the node's span tag.
    noLink: false, // Use < span > instead of < a > tag for this node
    activate: false, // Initial active status.
    focus: false, // Initial focused status.
    expand: false, // Initial expanded status.
    select: false, // Initial selected status.
    hideCheckbox: false, // Suppress checkbox display for this node.
    unselectable: false, // Prevent selection.
    // The following attributes are only valid if passed to some functions:
    children: null // Array of child nodes.
    // NOTE: we can also add custom attributes here.
    // This may then also be used in the onActivate(), onSelect() or onLazyTree() callbacks.
    },
    […]
]


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

[dynatree] TREE TO TREE DRAG AND DROP 예제  (0) 2012.02.21
[dynatree] Option 옵션  (0) 2012.02.09
[dynatree] dynatree (jQuery 기반의 tree-plugin)  (0) 2012.02.08
posted by 뚱2
var str = "<span id ='' />";
// 변경할 문자가 브라우져가 인식해서 할수 없이 띄어쓰기를 했다.
// 실제 변경할때는 변경할 문자들 사이에 공백이 없어야 한다.
str.replace(/<(\/?[a-zA-Z]+?.*?\/?)>/gmi, "& l t ; $1 & g t ;");

posted by 뚱2
$("#tree").dynatree({
    title: "Dynatree", // Tree's name (only used for debug outpu)
    minExpandLevel: 1, // 1: root node is not collapsible
    imagePath: null, // Path to a folder containing icons. Defaults to 'skin/' subdirectory.
    children: null, // Init tree structure from this object array.
    initId: null, // Init tree structure from a < ul >  element with this ID.
    initAjax: null, // Ajax options used to initialize the tree strucuture.
    autoFocus: true, // Set focus to first child, when expanding or lazy-loading.
    keyboard: true, // Support keyboard navigation.
    persist: false, // Persist expand-status to a cookie
    autoCollapse: false, // Automatically collapse all siblings, when a node is expanded.
    clickFolderMode: 3, // 1:activate, 2:expand, 3:activate and expand
    activeVisible: true, // Make sure, active nodes are visible (expanded).
    checkbox: false, // Show checkboxes.
    selectMode: 2, // 1:single, 2:multi, 3:multi-hier
    fx: null, // Animations, e.g. null or { height: "toggle", duration: 200 }
    noLink: false, // Use < span > instead of < a > tags for all nodes
    // Low level event handlers: onEvent(dtnode, event): return false, to stop default processing
    onClick: null, // null: generate focus, expand, activate, select events.
    onDblClick: null, // (No default actions.)
    onKeydown: null, // null: generate keyboard navigation (focus, expand, activate).
    onKeypress: null, // (No default actions.)
    onFocus: null, // null: set focus to node.
    onBlur: null, // null: remove focus from node.

    // Pre-event handlers onQueryEvent(flag, dtnode): return false, to stop processing
    onQueryActivate: null, // Callback(flag, dtnode) before a node is (de)activated.
    onQuerySelect: null, // Callback(flag, dtnode) before a node is (de)selected.
    onQueryExpand: null, // Callback(flag, dtnode) before a node is expanded/collpsed.

    // High level event handlers
    onPostInit: null, // Callback(isReloading, isError) when tree was (re)loaded.
    onActivate: null, // Callback(dtnode) when a node is activated.
    onDeactivate: null, // Callback(dtnode) when a node is deactivated.
    onSelect: null, // Callback(flag, dtnode) when a node is (de)selected.
    onExpand: null, // Callback(flag, dtnode) when a node is expanded/collapsed.
    onLazyRead: null, // Callback(dtnode) when a lazy node is expanded for the first time.
    onCustomRender: null, // Callback(dtnode) before a node is rendered. Return a HTML string to override.
    onCreate: null, // Callback(dtnode, nodeSpan) after a node was rendered for the first time.
    onRender: null, // Callback(dtnode, nodeSpan) after a node was rendered.

    // Drag'n'drop support
    dnd: {
        // Make tree nodes draggable:
        onDragStart: null, // Callback(sourceNode), return true, to enable dnd
        onDragStop: null, // Callback(sourceNode)
        // Make tree nodes accept draggables
        autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
        preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
        onDragEnter: null, // Callback(targetNode, sourceNode)
        onDragOver: null, // Callback(targetNode, sourceNode, hitMode)
        onDrop: null, // Callback(targetNode, sourceNode, hitMode)
        onDragLeave: null // Callback(targetNode, sourceNode)
    },
    ajaxDefaults: { // Used by initAjax option
        cache: false, // false: Append random '_' argument to the request url to prevent caching.
        timeout: 0, // >0: Make sure we get an ajax error for invalid URLs
        dataType: "json" // Expect json format and pass json object to callbacks.
    },
    strings: {
        loading: "Loading…",
        loadError: "Load error!"
    },
    generateIds: false, // Generate id attributes like < span id="dynatree-id-KEY" >
    idPrefix: "dynatree-id-", // Used to generate node id's like < span id="dynatree-id-<key>" >.
    keyPathSeparator: "/", // Used by node.getKeyPath() and tree.loadKeyPath().
    cookieId: "dynatree", // Choose a more unique name, to allow multiple trees.
    cookie: {
        expires: null // Days or Date; null: session cookie
    },
    // Class names used, when rendering the HTML markup.
    // Note: if only single entries are passed for options.classNames, all other
    // values are still set to default.
    classNames: {
        container: "dynatree-container",
        node: "dynatree-node",
        folder: "dynatree-folder",

        empty: "dynatree-empty",
        vline: "dynatree-vline",
        expander: "dynatree-expander",
        connector: "dynatree-connector",
        checkbox: "dynatree-checkbox",
        nodeIcon: "dynatree-icon",
        title: "dynatree-title",
        noConnector: "dynatree-no-connector",

        nodeError: "dynatree-statusnode-error",
        nodeWait: "dynatree-statusnode-wait",
        hidden: "dynatree-hidden",
        combinedExpanderPrefix: "dynatree-exp-",
        combinedIconPrefix: "dynatree-ico-",
        hasChildren: "dynatree-has-children",
        active: "dynatree-active",
        selected: "dynatree-selected",
        expanded: "dynatree-expanded",
        lazy: "dynatree-lazy",
        focused: "dynatree-focused",
        partsel: "dynatree-partsel",
        lastsib: "dynatree-lastsib"
    },
    debugLevel: 1 // 0:quiet, 1:normal, 2:debug
});

posted by 뚱2
posted by 뚱2
윈도우에서 javascript를 사용할수 있는 방법
CreateObject로 COM을 사용할수 있기때문에 조금만 머리 굴리면 웬만한건 다 될듯 하다.

링크 : http://msdn.microsoft.com/ko-kr/library/9bbdkx3k.aspx
Reference : http://msdn.microsoft.com/ko-kr/library/98591fh7.aspx
참고 : http://bybi.tistory.com/320


posted by 뚱2
참고 : 자바스크립트 완벽가이드 (JavaScript The Definitive Guide 5/E)

i : 대소문자를 구별하지 않는 매칭을 수행한다.
g : 전역 매칭을 수행한다. 즉, 첫 번째 매치에서 끝내지 않고 매치되는 모든 것을 찾는다.
m : 여러 줄 상태 ^는 줄의 시작이나 문자열의 시작에 매치되고, $는 줄의 끝이나 문자열의 끝에 매치된다.

1. search()
   이 메서드는 정규 표현식을 전달인자로 받아서 가장 처음 매칭되는 부분 문자열의 위치를 반환하고
   , 매칭되는 부분 문자열이 없다면 -1을 반환한다.
   * 정규표현식에서 g 플래그가 있으면 무시한다.

2. replace()
   이 메서드는 찾아서 바꾸기 작업을 수행한다.
   * 정규 표현식에 g 플래그가 설정되어 있으면 문자열내에서 패턴에 매치되는 무든 부분 문자열을 교체할 문자열로 바꾼다.
   * 정규 표현식에서 괄호로 묶인 부분 표현식은 왼쪽에서 오른쪽으로 번호가 매겨지고, 각 부분 표현식과 매치된 텍스트를 기억한다.
      만약 교체할 문자열에 $가 나오고 뒤따라 숫자가 나타나면 replace() 메서드는 $와 숫자를 부분 문자열에 매치된 텍스트로 바꾼다.

3. match()
    이 메서드는 정규 표현식을 유일한 전달인자로 받고 매치된 결과를 배열로 만들어 반환한다.
    , 매칭되는 부분 문자열이 없다면 null을 반환한다.


posted by 뚱2
var parent = {
	 method1 : function() {
	 }
};

var child = (function(parentObj) {
    var F = function(){
        this.method2 = function() {
        };
    };
    F.prototype = parentObj;
    return (new F());
})(parent);

console.log("method1" in child);// true
console.log("method2" in child);// true
console.log(child.hasOwnProperty("method1") );// false
console.log(child.hasOwnProperty("method2") );//true

초 간단 샘플예제이다.
객체에  메소드가 존재하는지 확인하는 방법은 hasOwnProperty 메소드와 in 연산자로 확인할수 있다.
다만 hasOwnProperty는 객체 자신의 메소드 인지 확인하는 것이고
in 연산자는 상속계통을 다 뒤져서 존재하는지 확인하는 메소드 이다.
posted by 뚱2

arguments.callee

This property is a reference to the function that you are in. Which is very handy if you want to get a reference to an anonymous function from inside itself. One good reason for doing this would be in a recursive anonymous function.

arguments.caller

This property is a reference to the function that called the function you are in. This allows you to get access to the entire current callstack which is very handy for debugging.


function test() {
    console.log(">>>test");
    console.log("arguments.callee\n" + arguments.callee);
    console.log("arguments.caller\n" + arguments.caller);
    console.log("arguments.callee.caller\n" + arguments.callee.caller);
    test1();
}

function test1() {
    console.log(">>>test1");
    console.log("arguments.callee\n" + arguments.callee);
    console.log("arguments.caller\n" + arguments.caller);
    console.log("arguments.callee.caller\n" + arguments.callee.caller);        
}    
test();

//  로그기록
//>>>test
//arguments.callee 
//function test() { 
//    console.log(">>>test"); 
//    console.log("arguments.callee\n" + arguments.callee); 
//    console.log("arguments.caller\n" + arguments.caller); 
//    console.log("arguments.callee.caller\n" + arguments.callee.caller); 
//    test1(); 
//}
//arguments.caller undefined
//arguments.callee.caller null
//>>>test1
//arguments.callee 
//function test1() { 
//    console.log(">>>test1"); 
//    console.log("arguments.callee\n" + arguments.callee); 
//    console.log("arguments.caller\n" + arguments.caller); 
//    console.log("arguments.callee.caller\n" + arguments.callee.caller); 
//}
//arguments.caller undefined
//arguments.callee.caller 
//function test() { 
//    console.log(">>>test"); 
//    console.log("arguments.callee\n" + arguments.callee); 
//    console.log("arguments.caller\n" + arguments.caller); 
//    console.log("arguments.callee.caller\n" + arguments.callee.caller); 
//    test1(); 
//}

위와 같이 오출하면 로그(firefox)이 찍힌다.
결국 arguments.callee 는 함수의 입장에서 자기자신
arguments.callee.caller 는 arguments.callee를 호출한 함수이다.
호출한 쪽이 함수가 아니라 전역환경이라면
arguments.callee.caller null 이다.
arguments.callee는 익명함수의 재귀호출에 유용하다.

* 추가적으로 callee, caller가 null이거나 undefined가 아닐때
Object.prototype.toString.call(arguments.callee);
Object.prototype.toString.call(arguments.callee.caller);
호출해 보면은 둘다 [object Function]을 리턴하는것을 알수 있다.


posted by 뚱2
jQuery를 이용해서 만들었다.
기본적으로 jQuery를 임포트 해야 한다.

var myStringify = function(data) {
    var  msg           = ""
        ,myData        = data || {}
        ,mySection     = ","
        ,isData        = false
        ,dataType      = jQuery.type(myData)
        ;
          
    // 배열인지 검사
    if ( dataType == "array" ) {
        msg += "[";
    }
    else if ( dataType == "object" ) {
        msg += "{";
    }
      
    jQuery.each(myData, function(k, v) {
        isData = true;
        var propertyType = jQuery.type(v);
         
        if ( propertyType == "array" || propertyType == "object" ) {
            if ( dataType == "array" ) {
                msg += arguments.callee(v);
            }
            else {
            	msg += "\"" + k + "\":" + arguments.callee(v);                    	
            }
            msg += mySection;
        }
        else {
            if ( dataType == "array" ) {
                msg += v;
            }
            else {
                msg += "\"" + k + "\":";
                if ( propertyType == "string" ) {
                    msg += "\"" + v + "\"";
                }
                else {
                	msg += "" + v;
                }
            }
            msg +=  mySection;
        }
    });//jQuery.each(myData, function(k, v) {
  
    if ( isData == true ) {
        msg = msg.substring(0, msg.length-1);
    }
  
    if ( dataType == "array" ) {
        msg += "]";
    }
    else if ( dataType == "object" ) {
        msg += "}";
    }
  
    return msg;
};//var myStringify = function(data) {


posted by 뚱2

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

[dynatree] TREE TO TREE DRAG AND DROP 예제  (0) 2012.02.21
[dynatree] dynatree node option  (0) 2012.02.09
[dynatree] Option 옵션  (0) 2012.02.09
posted by 뚱2


1. 제   목 : 자바스크립트 코딩 기법과 핵심 패턴 ( JavaScript Patterns)
2. 출판사 : 인사이트
3. 저   자 : 스토얀 스테파노프 / 김준기, 변유진 역
4. 가   격 : 22,000원
5. 난이도 : 초중급 (★★★★☆)
6. 판   매 : 판매중
7. 평   가 : ★★★★☆

이 책은 자바스크립트를 배우기 위해서 보는 책은 아닙니다.
자바스크립트를 어느정도 공부하신분이 자바스크립트를 효율적인 방법 및 패턴을 배우는 책입니다.
기존 Gof의 패턴은 Java나 C++로 배우게 되는데 이 책은 패러다임이 특히 다른 언어 (자바스크립트는 C계열의
문법을 사용하지만 java난 C++가 패러다임이 많이 다르다고 생각합니다.)인 자바스크립트를 이용해서
패턴을 설명하는 부분이 다른 어떤 자바스크립트 책에서도 찾아볼수 없는 유용한 부분인것 같습니다.
그리고 실무에 바로 사용해도 도움이 되는 패턴(네임스페이스 패턴, 샌드박스패턴)이 있습니다.
번역도 이해하는데 무리 없습니다.

제가 생각하는 자바스크립트 공부 순서는

1. 자바스크립트 완벽 가이드 (http://kangcom.com/sub/view.asp?sku=200805090006&mcd=571)
2. 자바스크립트 성능 최적화 (http://kangcom.com/sub/view.asp?sku=201109160003&mcd=571)
   - 2장의 설명이 자바스크립트 스코프를 이해하기 좋아서 순서를 올렸습니다.
3. 더글라스 크락포드의 자바스크립트 핵심 가이드 (http://kangcom.com/sub/view.asp?sku=200809180003&mcd=571)
4. 자바스크립트 코딩 기법과 핵심 패턴 (http://kangcom.com/sub/view.asp?sku=201111020003&mcd=571)


이 순서로 공부하시면 자바스크립트를 어느정도 편하게 사용하실수 있을 것 같습니다.
posted by 뚱2


1. 제   목 : High Performance Javascript 자바스크립트 성능 최적화
2. 출판사 : 한빛미디어
3. 저   자 : 니콜라스 자카스 지음 / 한성용 옮김

4. 가   격 : 20,000원 
5. 난이도 : 초중급 (★★★
)
6. 판   매 : 판매중
7. 평   가 : 


거두 절미하고 Chapter 2 데이터 접근 항목 내용만으로도 책의 값어치를 합니다.
'2.01. 스코프 관리'는 자바스크립트의 변수 스코프를 이해 할수 있게 그림과 같이 설명하고 있습니다.
'2.02 객체 멤버'는 그림과 함께 자바스크립트이 프로토타입 체인을 설명하고 있습니다.
개인적으로 자바스크립트 스코프와 클로져때문에 여러 서적을 찾아봤는데
이 책을 보고 한번에 정리되었습니다.
프로토타입 체인은 객체를 어떻게 활용해야 하는지 기본기이기 때문에 중요합니다.
2장의 설명과 함께 함수와 메소드등에 따라 this가 어떻게 변하는지 인지하신다면
자바스크립트의 객체를 자유로이 사용하시는데 불편함이 없을 것 같습니다.

posted by 뚱2

위와 같은 폼이 있습니다.
조건을 선택하고 검색 버튼을 클릭하면은 해당 결과가 아래의 그리드에 나타납니다.
조건 TEXT에 입력하고 Enter키를 누르면 검색 버튼을 클릭하는것도 같은 효과를 나타내주고 싶을때 입니다.


onSubmit="return false;" 꼭 작성해 주셔야 클릭시에 폼이 자동으로 전송되는건 막아줍니다.
* onSubmit="return false;" 하는 이유 : http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=qna_html&wr_id=155693

jQuery(document).ready(function($) {
    $("#listForm input[name=srch_text]").keydown(function(e){
        if(e.keyCode == 13){
            e.cancelBubble = true;
            $("#btn_search").click();
            return false;
        }
    });
});
keyDown이벤트를 잡고 enter키를 확인합니다. 이벤트가 전파되지 않게 e.cancelBubble 를 true 넣어줍니다.



posted by 뚱2
jQuery의 serializeArray를 이용한다.



위의 폼을 var arr = $("#listForm").serializeArray()를 호출하면
// 아래와 같은 arr의 형태로 생성된다.
arr = [
    {name : 'test_01', value : '1'}
   ,{name : 'test_02', value : '2'}
   ,{name : 'test_03', value : '3'}
];

그래서 위의 serializeArray 메소드를 이용해서 json형태로 만들어준다.
/**
 * jqGrid
 * desc   : form의 데이터를 json 형태로 변환해 준다.
 * return : 성공시에는 객체(JSON)을 리턴한다. 실패시에는 null을 리턴한다.
 */
jQuery.fn.serializeObject = function() {
	var obj = null;
	try {
		if ( this[0].tagName && this[0].tagName.toUpperCase() == "FORM" ) {
			var arr = this.serializeArray();
			if ( arr ) {
				obj = {};
				jQuery.each(arr, function() {
					obj[this.name] = this.value;
				});				
			}//if ( arr ) {
 		}
	}
	catch(e) {alert(e.message);}
	finally  {}
	
	return obj;
};



posted by 뚱2
구글에서 jQuery를 항상 최신으로 유지시켜주는 URL이다.
개발할때 유용할 듯 하다.

* 1.X.X 버전 지원 (jQuery 버전이 업데이트 되면 같이 업데이트 된다.)
경량화 버전 :  https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
일반 버전 : https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js







posted by 뚱2

if ( typeof test == 'undefined' ) 
    var test = {};

test.getIEVersion = function() {
    var myAgent = navigator.userAgent;
    var result = myAgent.match( /MSIE\s(\d{1,2}\.\d{1})/i );
    var retString = "";
    if ( result == null ) {
        retString = "none";
    }
    else {
        retString = result[1];
    }

    return retString;
};

alert(test.getIEVersion());



posted by 뚱2

if ( typeof test == 'undefined' )
    var test = {};

test.getBroswerName = function() { 
    // 아래에 검색할 브러우져 이름을 추가한다.
    var myAgent = [
         "MSIE"
        ,"FIREFOX"
        ,"CHROME"
    ];
    var currentAgent = navigator.userAgent;
    currentAgent = currentAgent.toUpperCase();
    
    for (var i = 0; i < myAgent.length; i++ ) {
        if ( currentAgent.indexOf(myAgent[i].toUpperCase()) != -1 ) {
            return myAgent[i];
        }
    }

    return "NONE";
};


//사용방법
alert(test.getBroswerName());

posted by 뚱2