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

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형
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);











반응형