반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형
Replace two events by a single


요 전 글에서 두개의 이벤트를 생성했죠? 글자 색(changecolor) 바꾸는 거랑 배경색(changebackgroundcolor) 바꾸는 거요.

이 두개의 이벤트를 changecolors event라는 하나의 이벤트를 call 해서 사용하도록 할 수 있습니다. 각 이벤트 마다 하나씩의 색을 전달하는 대신 두개의 파라미터에 두개의 색이 한번에 전달 되야겠죠.



New setColor () method managing changecolors event


setColors : function (color, backgroundcolor)

{

  var $elem = this.element;

      

  if (color != this.options.color || 

      backgroundcolor != this.options.backgroundColor) 

    $elem.trigger ("changecolors", [color, backgroundcolor]);

      

  this.options.color = color;

  this.options.backgroundColor = backgroundcolor;

  $elem.css ( { "background-color" : this.options.backgroundColor, 

                color : this.options.color } );

},



Taking account of the changecolors event


$("#plug1").bind ("changecolors", function (event, color, backgroundcolor)

{

  alert ("changecolors : \n" + "color = " + color + 

         "\n backgroundcolor = " + backgroundcolor);

});



이것을 처리하는 메소드는 이벤트 파라미터로부터  colorbackgroundcolor 이렇게 두개의 파라미터를 받습니다.

다른식으로 작성할 수도 있습니다. color and backgroundcolor properties 들을 포함한 객체를 만들어서 single parameter로 전달할 수도 있죠.



color and backgroundcolor transmitted in an object


setColors : function (color, backgroundcolor)

{

  var $elem = this.element;

      

  if (color != this.options.color || 

      backgroundcolor != this.options.backgroundColor) 

    $elem.trigger ("changecolors", 

         [ { color : color, backgroundcolor : backgroundcolor } ]);

      

  this.options.color = color;

  this.options.backgroundColor = backgroundcolor;

  $elem.css ( { "background-color" : this.options.backgroundColor, 

                color : this.options.color } );

},



여기서 전달된 객체에는 color and backgroundcolor properties 두 개가 있습니다.



Taking account of the event changecolors


$("#plug1").bind ("changecolors", function (event, colors)

{

  alert ("changecolors : \n" + "color = " + colors.color + 

         "\n backgroundcolor = " + colors.backgroundcolor);

});






Components already defined in jQuery Mobile


지금까지 여러분의 컴포넌트를 생성하는 방법을 보았습니다. jQuery Mobile에서도 이런 식으로 이미 만들어져 있는 컴포넌트들이 있는데요. 이 컴포넌트들은 여러분들이 쉽게 사용하실 수 있습니다.


아래 몇개의 샘플이 있는데 이 외에도 많이 있습니다.


Standard components of jQuery Mobile


Name

Signification

page

Windows management in the page

checkboxradio

Checkboxes and radio buttons management

textinput

Input texts management

selectmenu

Select menus management

button

Buttons management

slider

Sliders management

collapsible

Accordion menus management

listview

Listviews management

dialog

Overlapped windows management

navbar

Navigation bars management



나중에 다룰 컴퍼넌트들이 있는데요. 이러한 컴퍼넌트들은 각각 생성할 때 create event가 만들어 집니다. : pagecreate, checkboxradiocreate, etc..


이 각각의 컴포넌트들은 자신의 _create () method를 정의합니다. 이것들은 DOM tree  안에 새로운 HTML element들을 만들게 되죠. 일반적으로 _create () method 정의 바로 전에 요 전에 우리가 만든 attributes 들 처럼 options object가 정의 됩니다.


selectmenu component 를 만들기 위해 정의 된 options object를 보세요.



Definition of options in selectmenu component of jQuery Mobile


$.widget( "mobile.selectmenu", $.mobile.widget, {
    options: {
        theme: null,
        disabled: false,
        icon: 'arrow-d',
        iconpos: 'right',
        inline: null,
        corners: true,
        shadow: true,
        iconshadow: true,
        menuPageTheme: 'b',
        overlayTheme: 'a',
        hidePlaceholderMenuItems: true,
        closeText: 'Close',
        nativeMenu: true,
        initSelector: "select:not(:jqmData(role='slider'))"
    },



HTML 안에 컴포넌트와 연결된 element 의 attribute 들과 이 option들이 연결돼 있다는 걸 보셨었죠? 그 의미는 뭐냐 하면 HTML 의 <select> element와 관련해서 data-theme, data-disabled, data-icon, 등을 사용할 수 있다는 걸 말합니다. 디폴트 값들은 jQuery Mobile 코드 안에 object 정의 부분에 정해져 있습니다.



반응형


반응형
Create and manage events on the component



컴포넌트 안에 새로운 이벤트를 생성할 수 있습니다.  컴포넌트와 연관된 엘리먼트에서 간단하게 trigger (eventName) method 만 call 해 주면 됩니다. 이 메소드는 jQuery 의 standard 메소드 입니다. 그 이벤트는 jQuery 에서 bind () method를 사용해서 manage 될 겁니다.


예를 들어 글자색이 바뀌고 배경색이 바뀌는 두개의 이벤트를 생성할 수 있습니다. (changecolor event, changebackgroundcolor event)


이 이벤트가 발생해서 글자색과 배경색이 바뀌면 setColor () method 부분을 alter 해야 합니다.

우선 컴퍼넌트 부분을 볼까요.



Trigger an event when the color changes


(function ($, undefined )

{

  // component definition

  $.widget ("mobile.myplugin", $.mobile.widget, 

  {

    options : {

      backgroundColor : "grey",

      color : "blue"

    },

    _create: function () 

    {

      var $elem = this.element;

      $elem.css ( { "background-color" : this.options.backgroundColor, 

                    color : this.options.color } );

    },

    show : function ()

    {

      var $elem = this.element;

      $elem.show ();

    },

    hide : function ()

    {

      var $elem = this.element;

      $elem.hide ();

    },

    setColors : function (color, backgroundcolor)

    {

      var $elem = this.element;

    

      if (color != this.options.color) 

        $elem.trigger ("changecolor", [color]);

      if (backgroundcolor != this.options.backgroundColor) 

        $elem.trigger ("changebackgroundcolor", [backgroundcolor]);

  

      this.options.color = color;

      this.options.backgroundColor = backgroundcolor;

      $elem.css ( { "background-color" : this.options.backgroundColor,

                    color : this.options.color } );

    },

    getColors : function ()

    {

      return { color : this.options.color, 

               backgroundColor : this.options.backgroundColor };

    }

  });

  // taking into account of the component when creating the window

  // or at the create event

  $(document).bind ("pagecreate create", function (e) 

  

    $(":jqmData(role=myplugin)", e.target).myplugin ();

  });

}) (jQuery);



trigger () method 는 첫번째 파라미터로 생성된 이벤트의 이름을 갖습니다. 그리고 두번째 파라미터로는 이벤트에 전달 될 내용을 배열로 갖습니다. (여기서는 [color] 와  [backgroundcolor]입니다.)


이 이벤트는 아래와 같이 자바스크립트에서 handle 될 수 있습니다.



Taking account of the event


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 

<body> 

<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>

  <div data-role=content>

    <p> Window content </p>  

    <div id=plug1 data-role=myplugin> 

      <p>This is my component</p>

    </div>

  </div>

</div>

</body>

</html>

<script>

$("#plug1").bind ("myplugincreate", function ()

{

  $(this).myplugin ("setColors", "white", "gainsboro");

  var colors = $(this).myplugin ("getColors");

  alert ("color = " + colors.color + 

         "\n backgroundColor = " + colors.backgroundColor);

});

$("#plug1").bind ("changecolor", function (event, color)

{

  alert ("changecolor : " + color);

});

$("#plug1").bind ("changebackgroundcolor", function (event, backgroundcolor)

{

  alert ("changebackgroundcolor : " + backgroundcolor);

});

</script>







convention10.html


myplugin3.js


반응형


반응형
Add methods to the component



지금까지 해온 예제에는 컴포넌트 안에 오직 _create () method 만 있습니다. 컴포넌트 밖에서는 사용되지 않는 메소드죠. (prefix "_"를 사용하는 것은 private method라는 의미입니다.). 이 콤포넌트에 외부로부터 call 해서 사용할 수 있는 여러분의 메소드를 추가해 넣을 수 있습니다.


컴포넌트에 show (), hide (), setColor (color, backgroundcolor) 그리고  getColor () methods 들을 정의하겠습니다.


  • The show () method to display the component,

  • The hide () method to hide it,

  • The setColor (color, backgroundcolor) method can change the colors used,

  • The getColor () method returns a { color, backgroundColor } object containing the colors currently in use.



Defining methods on the component


(function ($, undefined )

{

  // component definition

  $.widget ("mobile.myplugin", $.mobile.widget, 

  {

    options : {

      backgroundColor : "grey",

      color : "blue"

    },

    _create: function () 

    {

      var $elem = this.element;

      $elem.css ( { "background-color" : this.options.backgroundColor, 

                    color : this.options.color } );

    },

    show : function ()

    {

      var $elem = this.element;

      $elem.show ();

    },

    hide : function ()

    {

      var $elem = this.element;

      $elem.hide ();

    },

    setColors : function (color, backgroundcolor)

    {

      var $elem = this.element;

      this.options.color = color;

      this.options.backgroundColor = backgroundcolor;

      $elem.css ( { "background-color" : this.options.backgroundColor, 

                    color : this.options.color } );

    },

    getColors : function ()

    {

      return { color : this.options.color, 

               backgroundColor : this.options.backgroundColor };

    }

  });

  

  // taking into account of the component when creating the window

  // or at the create event

  $(document).bind ("pagecreate create", function (e) 

  

    $(":jqmData(role=myplugin)", e.target).myplugin ();

  });

  

}) (jQuery);



setColor () method는 options object에서 세팅할 때 받은 색을 저장합니다. 이렇게 색을 저장한 후에는 getColor () 같은 다른 메소드에서 그 저장된 값을 사용할 수 있게 됩니다.


컴포넌트에 새로운 메소드들을 정의했습니다. 이것을 어떻게 자바스크립트로 사용하는지에 대해 살펴 보겠습니다.


Use the methods created on the component


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 


<body> 


<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Window content </p>  

    <div id=plug1 data-role=myplugin> 

      <p>This is my component</p>

    </div>

  </div>

</div>


</body>

</html>


<script>


$("#plug1").bind ("myplugincreate", function ()

{

  $(this).myplugin ("setColors", "white", "gainsboro");

  var colors = $(this).myplugin ("getColors");

  alert ("color = " + colors.color + 

         "\n backgroundColor = " + colors.backgroundColor);

});


</script>



정의된 메소드들은 컴포넌트가 생성된 후에 사용 가능합니다. 그래서 myplugincreate event 가 사용  됩니다.


어떻게 컴포넌트에 있는 메소드를 call 하는지 잘 보세요.


Calling setColors () method of myplugin component


$(this).myplugin ("setColors", "white", "gainsboro");


메소드 이름이 invoke 할 때의 첫번째 인자 입니다. 그 다음에 사용 할 수 있는 파라미터들이 옵니다. 모든 인자들은 스트링으로 전달 됩니다.





convention09.html


myplugin2.js



반응형

Ajax 로 컴포넌트 사용하기

2012. 10. 3. 21:15 | Posted by 솔웅


반응형
Use the component with Ajax



Ajax call로 컴포넌트를 insert 하면 훨씬 다양하게 사용될 수 있습니다. 이렇게 Ajax 를 call 하는 두가지 방법을 알아보겠습니다. 컴포너트의 creation method를 정의하는 방법과 create event를 사용하는 방법 이렇게 두가지 입니다. 둘 다 결과는 같게 나옵니다.


Using the creation method of the component


myplugin () method를 사용하는 것은 Ajax로 myplugin component를 생성하는 첫번째 방법입니다. 컴포넌트의 creation method에는 컴포넌트와 같은 이름을 사용합니다. 그리니까 myplugin () method는 myplugin component를 생성할 겁니다.


Insert the component with Ajax using the myplugin () method


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 

<body> 

<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>

  <div data-role=content>

    <p> Window content </p>  

  </div>

</div>

</body>

</html>

<script>

$.ajax (

  url : "action.php", 

  complete : function (xhr, result)

  {

    if (result != "success") return;

    var response = xhr.responseText;

    $("#home div:jqmData(role=content)").append (response);

  

    $("#plug1").myplugin ();

  }

});  

</script>



myplugin () method call은 HTML 안에서 이루어 졌습니다.


action.php file


<?
$html = "";
$html .= "<div id=plug1>";
$html .=   "<p>This is my component</p>";
$html .= "</div>";

  
echo utf8_encode ($html);
?>


action.php


convention08.html


myplugin.js

(Apache,PHP 서버 까신 후 로컬에서 테스트 해 보세요.)


Using create event


Using the create event is the second approach to create a component with Ajax.

create event를 사용하는 것은 Ajax로 컴포넌트를 생성하는 두번째 접근법입니다.


Insert the component with Ajax using the create event


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 

<body> 

<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>

  <div data-role=content>

    <p> Window content </p>  

  </div>

</div>

</body>

</html>

<script>

$.ajax (

  url : "action.php", 

  complete : function (xhr, result)

  {

    if (result != "success") return;

    var response = xhr.responseText;

    $("#home div:jqmData(role=content)").append (response);

        $("#home").trigger ("create");

  }

});  

</script>



create event는 컴포넌트를 포함한 HTML element에서 generate 됩니다. (여기서는는 idenrifire 가 home임 )


action.php file


<?
$html = "";
$html .= "<div id=plug1 data-role=myplugin>";
$html .=   "<p>This is my component</p>";
$html .= "</div>";
  
echo utf8_encode ($html);
?>


이전 PHP 코드와 다른 점은  컴포넌트를 정의할 때 data-role="myplugin" attribute 를 반드시 정해줘야 한다는 겁니다.  그렇게 하면 플러그인된 자바스크립트에서와 같이 create event가 진행될 때 이 attribute가 있는 HTML element를 찾게 됩니다.





convention09.html


myplugin.js


action.php



create event processing in the plugin


// taking into account of the component when creating the window

// or at the create event

$(document).bind ("pagecreate create", function (e) 

  $(":jqmData(role=myplugin)", e.target).myplugin ();

});



e.target parameter는 identifier가 home으로 지정된 identifier 가 있는 <div> element 와 연계 됩니다. 이것이 create event 유발하는 element 입니다.


The <div> element associated with the window causes the create event


$("#home").trigger ("create");


반응형


반응형
Pass parameters to the component



HTML 안에서 attributes를 통해서 jQuery Mobile 컴포넌트에 파라미터들을 전달할 수 있습니다. 예를 들어 element의 배경색과 텍스트 색을 전달해야 할 때 컴포넌트 안에서 직접 코딩을 해 넣을 수도 있지만 파라미터로 색을 받아서 사용할 수도 있습니다.


이를 위해서 HTML 에서 컴포넌트에 전달 할 새 data-colordata-background-color attributes를 사용하겠습니다.


Transmitting the text color and background color of the element


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 


<body> 


<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Window content </p>  

    <div id=plug1 data-role=myplugin 

            data-color=white data-background-color=black>

      <p>This is my component</p>

    </div>

  </div>

</div>


</body>

</html>



이전 글에서 사용한 컴포넌트는 HTML에서 data-colordata-background-color attributes를  전달해도 그것이 무엇인지 모를겁니다. 그러니까 컴포넌트의 JavaScript 코드를 수정해야겠죠.


Using in the component the attributes passed in the HTML


(function ($, undefined )

{

  // component definition

  $.widget ("mobile.myplugin", $.mobile.widget, 

  {

    options : {

      backgroundColor : null,

      color : null

    },

    _create: function () 

    {

      var $elem = this.element;

      $elem.css ( { "background-color" : this.options.backgroundColor, 

                    color : this.options.color } );

    }

  });

  

  // taking into account of the component when creating the window

  // or at the create event

  $(document).bind ("pagecreate create", function (e) 

  

    $(":jqmData(role=myplugin)", e.target).myplugin ();

  });

  

}) (jQuery);



options property 를 만들었습니다. attribute같은 전달된 다양한 파라미터들을 포함하고 있죠. data-color attribute는 options color property와 매치 됩니다. data-background-color attribute는 backgroundColor property와 매치 되죠. 이 property들은 null로 initialized 됩니다. 왜냐하면 전달받은 값들이 거기에 할당 될 것이기 때문이죠.


위 코드에 있는 options object는 jQuery Mobile의 Internal mechanism에 의해서 HTML 에서 넘어온 value로 자동적으로 initialize 됩니다.


convention07.html


myplugin1.js



Check that this works:





만약 HTML에 attribute 가 할당돼 있지 않다면 그 component에서 사용되는 값은 options object에 정의된 것이 될 겁니다.  위에서는 두개 옵션이 null 로 세팅돼 있지만 color blue로 그리고 backgroundColorgray로 할당 되어있다고 한다면 HTML 에 값이 없을 경우 이 값들이 대입 될 겁니다.


Using the component without attributes


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 


<body> 


<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Window content </p>  

    <div id=plug1 data-role=myplugin> 

      <p>This is my component</p>

    </div>

  </div>

</div>


</body>

</html>



Using default values in the attributes


(function ($, undefined )

{

  // component definition

  $.widget ("mobile.myplugin", $.mobile.widget, 

  {

    options : {

      backgroundColor : "grey",

      color : "blue"

    },

    _create: function () 

    {

      var $elem = this.element;

      $elem.css ( { "background-color" : this.options.backgroundColor, 

                          color : this.options.color } );

    }

  });

  

  // taking into account of the component when creating the window

  // or at the create event

  $(document).bind ("pagecreate create", function (e) 

  

    $(":jqmData(role=myplugin)", e.target).myplugin ();

  });

  

}) (jQuery);











반응형


반응형
Be warned of the creation of the component



JavaScript에서 myplugin component를 사용하기 위해 jQuery Mobile은 이 컴포넌트가 생성되는 마지막 단계를 가리키는 이벤트를 generate 합니다. 그 이벤트는  myplugincreate 입니다. ie  그 컴포넌트 이름은 스트링 "create"와 연결 됩니다.


이 이벤트는 jQuery의 standard method들과 같이 사용됩니다. 예를 들어 bind ()live ()같은 메소드들입니다.


Using the creation event of the component


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 

<body> 

<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>

  <div data-role=content>

    <p> Window content </p>  

    <div id=plug1 data-role=myplugin>

      <p>This is my component</p>

    </div>

  </div>

</div>

</body>

</html>

<script>

$("#plug1").bind ("myplugincreate", function ()

{

  alert ("Component created!");

});

</script>



이 이벤트는 그 컴포넌트가 create 됐는지를 알아 낼 때 유용하게 사용될 수 있을 겁니다. 예를 들어 컴포넌트에서 정의 된 메소드를 사용해야 할 경우 등이 되겠죠.




반응형


반응형
Create and use a component


jQuery Mobile 컴포넌트는 $.widget () method를 사용해서 만듭니다. 이 메소드는 컴포넌트를 생성하고 initialize 하며 이 안에 여러분이 원하는 메소드를 넣어서 사용하실 수 있습니다.


컴포넌트를 생성하기 위해서는 _create () method를 정의하고 나서 _init () method를 정의함으로서 initialize 할 수 있습니다. _create () method는 필수 입니다. 위 두 메소드의 다른 점은 실행 순서가 다릅니다. 즉 _create () method는 _init () method 이전에 실행 됩니다.


jQuery Mobile component를 만들기 위해 일반적으로 그 컴포넌트를 포함하고 있는 JavaScript 파일을 만들죠. 그 자바스크립트 파일은 HTML page 에서 <script> tag를 사용해서 include 될 수 있습니다. 그러면 자바스크립트 안에 있는 메소드에 접근해서 사용할 수 있게 됩니다.


실습을 해 보죠. 일단 아래 소스코드를 가지고 있는 myplugin component 를 만들겠습니다. myplugin.js file을 만들어서 그 안에 넣으시면 됩니다.



Creating a component (file myplugin.js)


(function ($, undefined )

{

  // component definition

  $.widget ("mobile.myplugin", $.mobile.widget, 

  {

    _create: function () 

    {

      var $elem = this.element;

      $elem.css ( { "background-color" : "black", color : "white" } );

    }

  });

  

  // taking into account of the component when creating the window

  // or at the create event

  $(document).bind ("pagecreate create", function (e) 

  

    $(":jqmData(role=myplugin)", e.target).myplugin ();

  });

  

}) (jQuery);



이 컴포넌트는 특정 element의 style을 바꾸는 일을 합니다.  배경색과 글자 색을 바꾸죠. 배경색은 검정이고 글자색은 흰색이 될 겁니다.


$.widget () method가 이 플러그인의 첫번째 parameter 죠? 일반적으로 컴포넌트의 진행 순서는 같습니다. _create () method는 this.element를 통해서 그 메소드를 사용할 HTML element에 접근하게 됩니다.  this.element의 value는 그 HTML element와 연결된 jQuery 클래서 객체 입니다.


pagecreatecreate events를 다루는 부분을 잘 보세요. 이 둘중의 한 이벤트가 발생하면 data-role=myplugin attribute를 가지고 있는 모든 HTML element들을 찾을 겁니다.  그 부분이 바로 이벤트가 일어나는  e.target인 거죠. 그리고 나서 이것을 myplugin () method를 사용해서 myplugin component에 전달해 줍니다. 이 메소드를 부르는 것은 그 내부의 _create () method를 시작하도록 해서 컴포넌트를 create 하게 하죠.


이렇게 하면 이제 HTML page에서 이 컴포넌트를 사용할 수 있게 되는 겁니다. HTML 페이지 안에 data-role="myplugin" attribute를 <div> element안에 정의 합니다. 그렇게 함으로서 새로운 component에 연결 되도록 만들 수 있습니다.



Using the component in an HTML page


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

  <script src=jquery.mobile/myplugin.js></script>

</head> 


<body> 


<div data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Window content </p>  

    <div id=plug1 data-role=myplugin>

      <p>This is my component</p>

    </div>

  </div>

</div>


</body>

</html>



HTML 파일안에서 myplugin.js file을 include 하는 것을 보세요. 그리고 data-role="myplugin" attribute 가 있는 <div> element를 보시구요. 이 부분이 컴포넌트가 적용 될 부분이죠.

이 HTML page를 브라우저에서 열면 _create () method 안에서 지정한 style이 작동해서 해당 div 안에 있는 텍스트의 배경색과 글자 색을 바꾸게 됩니다.




myplugin.js


convention05.html


반응형

Virtual Events 알아보기

2012. 9. 30. 22:54 | Posted by 솔웅


반응형

Virtual Events


virtual event들을 사용하는 이유는 HTML element를 trigger 할 수 있는 손가락이나 mouse 와 관련된 이벤트들을 표준화 하기 위해서 입니다. 이러한 이벤트들은 서로 다른 이름들을 가지고 있습니다. (eg touchstart and click for click type events, or touchmove and mousemove to move type events) jQuery Mobile 은 virtual events라고  하는 것을 만들어서 이러한 이벤트들의 이름을 표준화 했습니다.


Virtual events

Name

Signification

vclick

Idem click. Warning: jQuery Mobile developers recommend not to use the vclick event when it produces a change in the display (eg click on a link that shows a new window), because the vclick event is sometimes triggered two times - instead of one - when set on a particular element. In these cases, they recommend using click instead. Apart from these elements that can cause problems, we will use vclick.

vmousemove

Idem mousemove.

vmouseover

Idem mouseover.

vmousedown

Idem mousedown.

vmouseup

Idem mouseup.

vmouseout

Idem mouseout.

vmousecancel

Idem mousecancel.


아래 예제는 윈도우에서 어떤 이벤트가 발생 했을 때 그 이벤트의 이름을 화면에 보여 줍니다.


Detect and display the virtual events


<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script src=jquery.mobile/jquery.mobile.js></script>

</head> 


<body> 


<div id=home data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Events </p>

  </div>

</div>


</body>

</html>


<script>


var $content = $("#home div:jqmData(role=content)");


$("#home").bind ("vmouseover", function (event)

{

  $content.append (event.type + ", ");

});


$("#home").bind ("vmousedown", function (event)

{

  $content.append (event.type + ", ");

});


$("#home").bind ("vmousemove", function (event)

{

  $content.append (event.type + ", ");

});


$("#home").bind ("vmouseup", function (event)

{

  $content.append (event.type + ", ");

});


$("#home").bind ("vclick", function (event)

{

  $content.append (event.type + ", ");

});


$("#home").bind ("vmouseout", function (event)

{

  $content.append (event.type + ", ");

});


$("#home").bind ("vmousecancel", function (event)

{

  $content.append (event.type + ", ");

});


</script>







convention04.html



반응형

네임 스페이스 사용하기

2012. 9. 30. 22:40 | Posted by 솔웅


반응형

Using NameSpace


jQuery Mobile 은 data 라는 글로 시작하는 수 많은 attributes 를 사용합니다. 예를 들어 data-role, data-icon, 등이 있습니다. 이러한 attributes들은 jQuery Mobile에서는 아주 의미 있는 것들입니다. 이러한 attribute들이 original HTML 코드를 좀 더 enhance 된  display 를 보여 주도록 합니다.


그런데 이렇게 jQuery Mobile 이 사용하고 있는 attribute들을 다른 library 도 한 두개 사용하고 있다면 어떻게 될까요? 그러면 OS에서는 혼동스럽겠죠.


이러한 문제를 해결하기 위해 jQuery Mobile은 namespaces를 사용합니다. 대부분 data 글자 다음에 추가 됩니다. 아마 data라는 글자로 시작하는 attributes를 가지고 있는 library들은 많을 겁니다. jQuery Mobile을 포함해서요. 하지만 data 뒤에 특별한 name space를 붙이면 같아지지 않겠죠. 예를 들어 data-role 이라는 이름이 중복되지 않게 하기 위해 data-my-role를  사용할 수 있겠죠. 여기서 가 나름대로의 namespace "my-"가 될 수 있을 겁니다.


Indicate the namespace in the HTML page


$.mobile.ns가 namespace로 사용됩니다.  만약 namespace 가 사용되지 않으면 jQuery Mobile은 "" 을 사용합니다. 즉 classic 한 data-role, data-icon, 등을 사용하게 되는거죠.


"ns1-" namespace를 사용하도록 할 수 있습니다.  namespace 끝에 "-"가  붙은것을 잘 봐 두세요. attributes에 space를 사용하지 않고 이것을 많이들 사용하죠.


Using the "ns1-" namespace

<!DOCTYPE html>

<html> 

<head> 

  <meta name=viewport content="user-scalable=no,width=device-width" />

  <link rel=stylesheet href=jquery.mobile/jquery.mobile.css />

  <script src=jquery.js></script>

  <script>

    $(document).bind ("mobileinit", function ()

    {

      $.mobile.ns = "ns1-";

    });

  </script>  

  <script src=jquery.mobile/jquery.mobile.js></script>

</head> 


<body> 


<div id=home data-ns1-role=page id=home data-ns1-theme=e>

  <div data-ns1-role=header>

    <h1>Home</h1>

  </div>


  <div data-ns1-role=content>

    <p> Window content </p>

  </div>

</div>


</body>

</html>



$.mobile.ns
의 값을 바꾸기 위해 mobileinit event를 사용했습니다. 그리고 그 값을 jQuery Mobile에서 사용하도록 만들었죠.


그리고 나서  data-ns1-role (instead of data-role) 과 data-ns1-theme (rather than data-theme) attributes 들을 사용합니다. 만약 여기서 data-roledata-theme attributes들을 사용하면 작동되지 않을 겁니다.





Access to the attribute in JavaScript code


data-role attribute 가 namespace "ns1-"를 사용해서 data-ns1-role로 사용되는 것을 위에서 보셨습니다. 그렇게 하면 자바스크립트 안에서 data-ns1-role attribute name을 사용할 수 있게 되는 건데요.  아래와 같이도 사용할 수 있습니다.


First form of writing (to be avoided)

alert ($("div#home").attr ("data-ns1-role"));

위와 같이 namespace를 사용할 수도 있고,


Second form of writing (best)

alert ($("div#home").attr ("data-" + $.mobile.ns + "role"));

위와 같이 원래의 $.mobile.ns 를 사용할 수 있습니다.


두번째 것은 namespace 값을 사용하지 않은 거죠. 이렇게 하면 나중에 namespace를 한꺼번에 바꾸어야 될 때 유용하겠죠. 즉 유지, 관리가 용이하게 됩니다.


또한 jQuery Mobile 에서는 이 writing 을 좀 더 간편하게 사용하도록 하는 메소드를 제공하고 있습니다. jqmData (name) method가 그것입니다.


Third form of writing (optimal)

alert ($("div#home").jqmData ("role"));


jqmData (name) method는 "data-"name스트링과 함께 namespace의 연속성을 허용하고 해당 attribute의 값을 retrieve 합니다.  그 attribute 값의 retrieve를 위한 attr () jQuery method는 더이상 사용하지 않습니다.  jqmData () method로 교체 됐죠.


jqmData (name) and jqmData (name, value) methods


jqmData () methods를 사용하는 목적은 jQuery attr () method를 사용하지 않고 해당 attribute들을 관리할 수 있도록 하기 위함 입니다.


Methods managing attributes

Method

Signification

jqmData (name)

Get the value of the data-xxx-name attribute, for example data-ns1-role.

jqmData (name, value)

Set the value of the data-xxx-name attribute, for example data-ns1-role.


Get the theme associated with the window

alert ($("div#home").jqmData ("theme"));


Set the theme associated with the window

$("div#home").jqmData ("theme", "a");


Access to the attribute in selectors


attribute들의 관리를 제대로 하기 위해 jQuery Mobile은 selector들을 사용할 때 이것을 manage 할 수 있도록 방법을 제공하고 있습니다. 여기에 jqmData (value) pseudo-class를 생성하는 이유입니다.


First form of writing (to be avoided)

alert ($("div[data-ns1-role=page]").html ());

위와 같이 하는 대신에 아래와 같이 할 수 있습니다.


Second form of writing (best)

alert ($("div[data-" + $.mobile.ns + "role=page]").html ());


jqmData (value) pseudo class와 같이 사용하면 아래와 같이 됩니다.


Third form of writing (optimal)

alert ($("div:jqmData(role=page)").html ());


여기서 value parameter는 "role=page" 입니다. data-role attribute (including any namespace)가 "page"<div> elements 를 get 하기 위함이죠.


만약 "role" string 만 사용한다면 data-role attribute가 있는 모든 <div> elements 들을 retrieve 할 겁니다.


All <div> elements with the data-role attribute set to any value

alert ($("div:jqmData(role)").length); // 3 elements: page, header, content


All <div> elements with the data-role attribute set to "page"

alert ($("div:jqmData(role=page)").length); // 1 element: page


반응형

Configuration Options

2012. 9. 29. 05:43 | Posted by 솔웅


반응형

Configuration Options



mobileinit event는 jQuery Mobile configuration options를 바꿀 수 있는 마지막 instant 입니다. 대부분의 옵션들에 대해 이 때 수정할 수 있습니다. 일부 이벤트들은 이 mobileinit event가 지나도 바꿀 수 있는 것들이 있습니다면 어쨌든 그 값들을 바꾸기 위해서는 항상 mobileinit event를 사용합니다. 만약 이 기간동안에 어떤 option의 값이 바뀌지 않으면 jQuery Mobile은 디폴트 값을 할당 합니다.


대부분의 이 option들은 jQuery Mobile에 의해 attribute들로 정의 됩니다.  예를 들어 data-icon, data-transition, data-back-btn-text, etc.. 같은 것 들이죠. HTML 코드에 이 attribute 값들이 정의되어 있지 않다면 디폴트 값이 할당 됩니다. 이 디폴트 값들이 mobileinit event이 진행되는 동안에 수정되어 질 수 있는 값들입니다.


General options


이 option들은 $.mobile object의 프로퍼티들입니다. 예를 들어 ns option은 $.mobile.ns 로 연결 되는 식이죠.


General options


Option

Signification

ns

Defines the namespace (see next section). Default "" (no namespace).

activePageClass

CSS class added to the <div> defining the window when it becomes active. Default "ui-page-active".

ajaxEnabled

Boolean indicating whether the HTML pages are retrieved by Ajax (if true) or not (if false). Default true. If the pages are not retrieved by Ajax, the previous windows are removed from the DOM.

defaultPageTransition

Default transition between two windows. Default "slide".

defaultDialogTransition

Default transition between two windows, one of which is superimposed. Default "pop".

loadingMessage

Message displayed to indicate that a HTML page is being loaded. Default "loading". This option can be changed outside the mobileinit event processing.

pageLoadErrorMessage

Message displayed to indicate an HTML page could not be loaded successfully. Default "Error Loading Page".

autoInitializePage

Boolean indicating if we let jQuery Mobile make himself the first window display. If true (default) the $.mobile.initializePage () is automatically called by jQuery Mobile allowing to display the first window. If false, it will be in our program to do this first viewing (calling ourselves the $.mobile.initializePage ()).


Options managing windows


이 옵션들은  $.mobile.page.prototype.options의 프로퍼티 들입니다. 예를 들어 backBtnText option은  $.mobile.page.prototype.options.backBtnText로 연결 되는 식이죠


Options managing windows


Option

Signification

backBtnText

Sets the text displayed on the Back button. Default "Back".

addBackBtn

Boolean indicating whether the Back button will be displayed in the window. Default false (not displayed).

backBtnTheme

Theme ("a", ..., "e") associated with the Back button. Default null, indicating to use the theme of the enclosing element.

keepNative

Selector specifying the HTML elements that should not be changed by jQuery Mobile into another HTML code. By default those whose data-role attribute is "none" or "nojs".

domCache

Boolean indicating whether the window should be stored in the DOM tree after it is no longer visible. This option only manages the windows that are not already present in the HTML page, ie those recovered by jQuery Mobile via Ajax. Default false (the windows loaded later are removed from the DOM when they become hidden).

theme

Theme ("a", ..., "e") associated with the window. Default "c".

headerTheme

Theme ("a", ..., "e") associated with the title bar. Default "a".

footerTheme

Theme ("a", ..., "e") associated with the bar at the bottom of page. Default "a".

contentTheme

Theme ("a", ..., "e") associated with the contents of the window. Default "".


Options managing lists


이 옵션들은 $.mobile.listview.prototype.options의 프로퍼티들입니다. theme option 같은 경우엔 $.mobile.listview.prototype.options.theme 이런 식으로 사용하시면 됩니다.


Options managing lists


Option

Signification

initSelector

Selector for finding lists in the HTML page. Default "jqmData (role='listview')".

theme

Theme ("a", ..., "e") associated with list items. Default "c".

countTheme

Theme ("a", ..., "e") associated with HTML elements with "ui-li-count" CSS class. Default "c".

dividerTheme

Theme ("a", ..., "e") associated to list items with the data-role="list-divider" attribute. Default "b".

filterTheme

Theme ("a", ..., "e") associated with the search field in the list.

inset

Boolean indicating whether the lists should be displayed with rounded edges. Default false.

filter

Boolean indicating whether to display a search field for list items. Default false.

filterPlaceHolder

String displayed in the search field of a list with the attribute data-filter="true". Default "Filter items ...".


Options managing navigation bars


이 옵션들은 $.mobile.navbar.prototype.options의 프로퍼티 들입니다. iconpos option 같은 경우엔 $.mobile.navbar.prototype.options.iconpos 이런 식으로 사용하시면 됩니다.


Options managing navigation bars


Option

Signification

initSelector

Selector for finding navigation bars in the HTML page. Default "jqmData (role='navbar')".

iconpos

Indicates the position of the icon ("top", "right ","bottom","left") when present in the buttons on the navigation bar. By default "top".

grid

Specifies the maximum number of buttons that may appear in a line of the navigation bar ("a" for 2 buttons max, "b" for 3, "c" for 4 and "d" for 5. By default null, indicating the place buttons at best.


Options managing buttons


이 옵션들은 $.mobile.button.prototype.options의 프로퍼티 들입니다. theme option 같은 경우엔 $.mobile.button.prototype.options.theme이런식으로 사용하

Warning: 이 옵션들은 button() method 를 사용해서 버튼을 생성하면 해당 account 에 적용 됩니다.


Options managing buttons


Option

Signification

initSelector

Selector for finding buttons in the HTML page. Default "button, [type='button'], [type='submit'], [type='reset'], [type='image']".

theme

Theme ("a", ..., "e") associated with buttons. Default null, indicating to use the theme associated with the enclosing element.

icon

Icon associated with buttons. Default null (no icon).

iconpos

Position of the icon in buttons, when present. Default "left".

inline

Boolean indicating whether the width of the button adapts to its contents (if true), or falls of the width of the window (if false). Default false.

corners

Defines if the buttons have rounded edges (if true) or rectangular (if false). Default true (rounded edges).

shadow

Boolean indicating whether a shadow is associated with buttons. Default true (shaded buttons).

iconshadow

Boolean indicating whether a shadow is associated with the icons on the buttons. Default true (has shadow).


Options managing input fields


이 옵션들은 $.mobile.textinput.prototype.options의 프로퍼티 들입니다. theme option의 경우 $.mobile.textinput.prototype.options.theme이렇게 사용하시면 됩니다.


Options managing input fields


Option

Signification

initSelector

Selector for finding input fields in the HTML page. Default "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea".

theme

Theme ("a", ..., "e") associated with input fields. Default null, indicating to use the theme associated with the enclosing element.


Options managing checkboxes and radio buttons


이 옵션들은 $.mobile.checkboxradio.prototype.options의 프로퍼티 들입니다. theme option의 경우 $.mobile.checkboxradio.prototype.options.theme 이렇게 사용하시면 됩니다.


Options managing checkboxes and radio buttons


Option

Signification

initSelector

Selector for finding checkboxes and radio buttons in the HTML page. Default "input[type='checkbox'], input[type='radio']".

theme

Theme ("a", ..., "e") associated with checkboxes and radio buttons. Default null, indicating to use the theme associated with the enclosing element.



Options managing selection list



이 옵션들은 $.mobile.selectmenu.prototype.options의 프로퍼티 들입니다. theme option의 경우 $.mobile.selectmenu.prototype.options.theme 이렇게 사용하시면 됩니다.


Options managing selection lists


Option

Signification

initSelector

Selector for finding selection lists in the HTML page. Default "select:not(:jqmData( role='slider'))".

theme

Theme ("a", ..., "e") associated with elements of the selection list. Default null, indicating to use the theme associated with the enclosing element.

icon

Icon in the button associated with the selection list. Default "arrow-d" (arrow down).

iconpos

Position of the icon in the button associated with the selection list ("top", "rght", "bottom", "left"). Default "right".

inline

Boolean indicating whether the button for the selection list adjusts in width to its contents (if true) or spreads over the width of the window (if false). Default false.

corners

Defines if the buttons associated with the selection lists have rounded edges (if true) or rectangular (if false). Default true (rounded edges).

shadow

Boolean indicating whether a shadow is associated with the buttons associated with selection lists. Default true (shaded buttons).

overlayTheme

Theme ("a", ..., "e") associated with the border around the elements of the selection list. Default "a".

nativeMenu

Boolean indicating whether the selection list is displayed natively (if true) or so improved by jQuery Mobile (if false). Default true (selection list displayed natively).


Options managing sliders


이 옵션들은 $.mobile.slider.prototype.options의 프로퍼티 들입니다. theme option의 경우 $.mobile.slider.prototype.options.theme 이렇게 사용하시면 됩니다.


Options managing sliders


Option

Signification

initSelector

Selector for finding sliders in the HTML page. Default "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')".

theme

Theme ("a", ..., "e") associated with the cursor moves on the slider. Default null, indicating to use the theme associated with the enclosing element.

trackTheme

Theme ("a", ..., "e") associated with the axis on which the cursor moves. Default null, indicating to use the theme associated with the enclosing element.


Options managing accordion menus


이 옵션들은 $.mobile.collapsible.prototype.options의 프로퍼티 들입니다. theme option 의 경우 $.mobile.collapsible.prototype.options.theme 이렇게 사용하시면 됩니다.


Options managing accordion menus


Option

Signification

initSelector

Selector for finding accordion menus in the HTML page. Default ":jqmData(role='collapsible')".

theme

Theme ("a", ..., "e") associated with the accordion menu. Default null, indicating to use the theme associated with the enclosing element.

iconTheme

Theme ("a", ..., "e") associated with the icons in the accordion menu. Default "d".

collapsed

Boolean indicating whether the menu should be closed or open at startup. Default true (closed menu).


반응형