레이블이 Prototype인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Prototype인 게시물을 표시합니다. 모든 게시물 표시

2009년 11월 12일 목요일

JQuery 와 다른 라이브러리 충돌시.

http://docs.jquery.com/Using_jQuery_with_Other_Libraries



Using jQuery with Other Libraries

From jQuery JavaScript Library

Jump to: navigation, search

Contents

General

The jQuery library, and virtually all of its plugins are constrained within the jQuery namespace. As a general rule, "global" objects are stored inside the jQuery namespace as well, so you shouldn't get a clash between jQuery and any other library (like Prototype, MooTools, or YUI).

That said, there is one caveat: By default, jQuery uses "$" as a shortcut for "jQuery"

Overriding the $-function

However, you can override that default by calling jQuery.noConflict() at any point after jQuery and the other library have both loaded. For example:

 <html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();

// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});

// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>

This will revert $ back to its original library. You'll still be able to use "jQuery" in the rest of your application.

Additionally, there's another option. If you want to make sure that jQuery won't conflict with another library - but you want the benefit of a short name, you could do something like this:

 <html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function(){
$j("div").hide();
});

// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>

You can define your own alternate names (e.g. jq, $J, awesomeQuery - anything you want).

Finally, if you don't want to define another alternative to the jQuery name (you really like to use $ and don't care about using another library's $ method), then there's still another solution for you. This is most frequently used in the case where you still want the benefits of really short jQuery code, but don't want to cause conflicts with other libraries.

 <html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();

// Put all your code in your document ready area
jQuery(document).ready(function($){
// Do jQuery stuff using $
$("div").hide();
});

// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>

This is probably the ideal solution for most of your code, considering that there'll be less code that you'll have to change, in order to achieve complete compatibility.

Also see: Custom Alias

Including jQuery before Other Libraries

If you include jQuery before other libraries, you may use "jQuery" when you do some work with jQuery, and the "$" is also the shortcut for the other library. There is no need for overriding the $-function by calling "jQuery.noConflict()".

 <html>
<head>
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});

// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>

Referencing Magic - Shortcuts for jQuery

If you don't like typing the full "jQuery" all the time, there are some alternative shortcuts:

  • Reassign jQuery to another shortcut
    • var $j = jQuery;
    • (This might be the best approach if you wish to use different libraries)
  • Use the following technique, which allows you to use $ inside of a block of code without permanently overwriting $:
    • (function($) { /* some code that uses $ */ })(jQuery)
    • Note: If you use this technique, you will not be able to use Prototype methods inside this capsuled function that expect $ to be Prototype's $, so you're making a choice to use only jQuery in that block.
  • Use the argument to the DOM ready event:
    • jQuery(function($) { /* some code that uses $ */ });
    • Note: Again, inside that block you can't use Prototype methods

2008년 11월 13일 목요일

JQuery 를 이용한 html와 script 와 분리


요새 prototype.js 를 이용해, javascript 를 깔끔하게, 효율적으로

만드는 방안으로 생각 하고 있는 도중, JQuery 를 알게 되었다.

그런데 이게, JQuery 예제를 이용하던 도중 이것을 이용하면,

디자이너가 HTML를 넘기면 id 및 name 를 세팅하여, 넘겨주면,

스크립트 작업 후 개발을 할때, 디자인이 수정되어도, 가공된 페이지에 변경 없이 작업을 할수 가 있다고 생각이

들었다. Greate!!

물론 prototype 를 이용해 할수도 있는데 흠.. JQuery 를 이용하면 좀더 효율 적으로 할 수 있다.




<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<title>Untitled Document</title>

<script type="text/javascript" src="script/jquery-1.2.6.js"></script>
<script type="text/javascript">

 $(document).ready(
  function (){
   $("#textcubeLink").click(
    function(){
     alert("empas image click");
    }
   ).css("cursor", "pointer");
   
   $("#blogLink").click(
    function(){
     location.href = "http://taesuz.net/tt/";
    }
   ).css("cursor", "pointer");
   
   

  }
 
 
 );

</script>

<style type="text/css">
    .links { cursor: pointer; }
 </style>

</head>

<body>

<a id="blogLink">taesuz.net 링크</a>
<br />
<br />
<img src="http://taesuz.net/tt/skin/ReinerSchwarzKoreanisch/images/textcube.jpg" id="textcubeLink" />

</body>
</html>


보시다 시피, 분리가 될수 있다. html 디자인은 그대로 있지만, 링크나, 스크립트 제어 부분이 완전히 분리되어있다.

좀더 공부 하면, 보다 깔금하게 효율적으로 분리가 되어 제어 가능하지 않을까?

이 얼마나 알흠다운가 ㅎㅎ

앞으로 효율적으로 활용해 봐야겠다.

2008년 8월 12일 화요일

JSP, AJAX, Prototype, JSON, XML을 이용한 로그인 처리..


JSP, AJAX, Prototype, JSON을 이용한 로그인 처리.. 라고 타이틀은 지었지만,

이름 만큼 대단한 예제는 아니다.. 다만, 위의 언어들을 이용해서 만든 Refresh 없는 로그인 처리이다.

방식은 로그인 체크가 필요한 버튼이나 어떠한 행위가 이루어 질때, checkLogin() 을 호출.

loginCheck.jsp 를 불러온다. loginCheck.jsp 에는 JSON 타입으로, 세션체크를 하여, 로그인 여부를 판별한다.

checkLogin() -> loginCheck.jsp (세션 체크 후 JSON 생성) -> resultProc() 에서 처리

위와 같은 방식이 가능한 것은 브라우져의 세션은 현재 띄우고 있는 브라우져의 부모나 자식창에 세션이 상속되기

때문에 기존에 iFrame 으로 작업을 했으나, 새로고침을 해야 하는 번거로움이 있었다. 그러나 이방식은

새로고침이 필요없다.

우선, 로그인 처리를 할 페이지를 만들어 준다.

로그인 체크를 위핸 javascript 메소드를 만들어 준다. 이때, prototype.js 가 include 되어있어야 한다.


main.html
    [code]
    function checkLogin()
    {
    var url = './loginCheck.jsp?timeStamp=' + new Date().getTime();

     var myAjax = new Ajax.Request(
         url,
        {
           onComplete: resultProc,
           onException: onException
        });
     }

    function resultProc(req) {

        //JSON 방식
        var result = eval("(" + req.responseText + ")");
      
        if( result.data.result == 1 ){
            alert("로그인 되어있음");
           
        } else {
            goLogin();
       
        }
}
[/code]


loginCheck.jsp (JSON)
[code]
<%@ page contentType="text/plain; charset=euc-kr" %>
<%
String MEMBER_ID = "";
String result = "2";

if( session.getAttribute("MEMBER_ID")!=null ){
    MEMBER_ID = session.getAttribute("MEMBER_ID").toString();
    result = "1";
}

%>

{
   data: {
        result: '<%=result %>',
        memberid: '<%=MEMBER_ID %>'
       
    }
}
[/code]





위 방식을 xml 을 로드해서 처리 하려면 아래와 같이 바꾸면 된다.




main.html
[code]
    function resultProc(req) {
        var xmlDoc = req.responseXML;
        var result = xmlDoc.getElementsByTagName("result")[0].firstChild.nodeValue;
        console( result );
    }
[/code]


loginCheck.jsp (XML)
[code]
<?xml version="1.0" encoding="utf-8" ?>
<%@ page contentType="text/xml; charset=utf-8" %>
<%
String MEMBER_ID = "";
String result = "2";

if( session.getAttribute("MEMBER_ID")!=null ){
    MEMBER_ID = session.getAttribute("MEMBER_ID").toString();
    result = "1";
}

%>

<node>
    <result><%=result %></result>
</node>
[/code]


JSP로 XML를 파싱할떄 주의!! 꼭 위의 빨간 색 부분의 contentType 를 지정해 주어야 제대로 인식한다..

이것때문에 30분간 뻘짓.. -_-;