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

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

What's at risk for Rhode Island if the 'fiscal cliff' is not averted?


December 27, 2012 3:57 pm
By Philip Marcelo


PROVIDENCE, R.I. -- With the U.S. House set to reconvene Sunday on a possible "fiscal cliff" deal, millions of dollars in federal aid driving government services and significant parts of the Rhode Island economy hang in the balance, according to recent national studies.


PROVIDENCE, R.I. 미하원 입법위원회는 일요일 "fiscal cliff" 협의를 위해 재소집합니다. 이에 따라 연방정부가 지원하는 수십만 달러의 지원금을 주정부에 지원하고 주정부는 이를 경제 균형 발전에 사용할 수 있습니다.


Nearly $19 million of the total $254 million or so in federal funding the state receives annually for social service programs for the poor, children and seniors, as well as education and job training are at risk for automatic cuts, if a deal is not reached, according to a July study commissioned by the office of U.S. Sen. Tom Harkin, chairman of the Senate Committee on Health, Education, Labor and Pensions. 


연방정부의 전체 2천5백4십만불의 지원금 중 로드 아일랜드 주정부는 백9십만불 가량을 받을 예정이며 이는 저소득 계층과 어린이 그리고 노인계층을 위한 social service 프로그램에 사용될 예정입니다. 또한 교육과 job training 부문에도 일부 사용될 예정이지만 예산이 부족할 경우 지원이 중단될 수도 있다고 건강,교육,노동,연금 상원의원회 의장 Tom Harkin 상원의원은 말했습니다.


The state can also expect significant reductions in federal spending on defense procurement, salaries and wages, which account for 2.8 percent of Rhode Island's gross domestic product, according to a November report by the Pew Center on States.

Those come on top of the income tax hikes all taxpayers can expect to pay in the new year, as well as the expiration of federal benefits for some on unemployment.

또한 주정부는 로드 아일랜드의 총 생산중 2.8 퍼센트를 차지하는 조달과 임금, 급여 등에서도 연방정부 지원 규모 축소로 예산을 삭감 해야 되는 상황에 있습니다. 이러한 조치들은 새해 세금을 내야할 납세자들의 소득세 상승과 관련돼 있습니다. 또한 일부 실업자들에 대한 연방 정부 지원금도 새해부터는 중단 될 예정입니다.





이 기사는 지역신문인 Providence Journal 의 인터넷판 기사인데요.

아마 인터넷 판에는 기사의 일부분만 싣는 것 같습니다.

어쨌든 번역하기가 좀 어렵네요.


미국 연방정부의 fiscal cliff 때문에 로드 아일랜드 주에도 지원금도 삭감되고 중단되는 지원도 있고 해서 여러모로 어려워 지는군요.


저소득자나 실업자에 대한 지원도 줄어들 수 있고 무엇보다 소득세가 높아져서 제가 내야 할 세금도 더 늘어나겠네요.


Fiscal Cliff 를 막기 위해서는 공화당의 협조가 필요한데 공화당은 전제조건으로 오바마의 의료보험법 개정 관련 예산 삭감과 국방예산 삭감 취소 그리고 부자 감세를 요구하고 있습니다.


한마디로 공화당은 일반 국민들에게 돌아가는 혜택을 줄이고 무기 생산업자들 그리고 부자들의 소득을 늘리는 정책을 펴라는 요구네요.


어쩌면 이렇게 이명박근혜랑 똑 같은지.... 나쁜 놈들......







반응형


반응형

Databases on the client side


이번에 다루는 챕터는 jQuery Mobile 에서 제공하는 기능은 아닙니다. HTML5에서 제공하는 기능을 jQuery Mobile 이 활용하는 겁니다. HTML5는 요즘 브라우저에서 대부분 지원하고 있습니다. 특해 대부분의 스마트 폰이나 tablet 들의 브라우저에서도 지원하구 있습니다.


이 기능은 jQuery Mobile 의 기능과 같이 사용되면 아주 유용합니다. 원격 서버가 아닌 local database 에 저장된 데이터에 접근하기 위해 jQuery Mobile 과 함께 사용하는 자바스크립트 프로그램으로 그 기능을 구현할 수 있습니다.


HTML5 offers two types of data storage on the client:


  •  SQL로 만들어진 브라우저 내의 데이터베이스. 저장할 데이터가 많을 경우 이 저장방법을 사용할 수 있습니다.

  • localStorage and sessionStorage objects를 통한 저장공간. string 으로 만들어진 정보를 저장합니다. 데이터베이스보다 제한사항들이 적습니다. 그리고 구현하기가 간단합니다. 적은 양의 정보를 저장하는데 사용합니다.


Permanent storage and session storage


permanent storage 와 session storage의 다른 점은 저장기간에 있습니다.

permanent storage에서는 정보를 유저가 지울 때까지 저장합니다. 즉 그 application이 close 되도 phone 을 껐다가 켜도 그 데이터는 유지가 됩니다.


session storage는 정보가 그 세션의 context 내에서만 저장됩니다. 즉 세션에 저장된 정보는 우리가 만든 사이트의 모든 페이지에서 접근할 수 있지만 그 기간은 application 이 run 하고 있을 때 만입니다. 이 application 이 닫히거나 다른데로 넘어가 버리면 즉 세션이 끝나버리면 그 정보는 없어집니다.


이 두 기능을 구현하기 위해서는 다음 두개의 JavaScript 객체들을 사용하시면 됩니다. : localStorage and sessionStorage:


  • localStorage allows permanent storage,

  • sessionStorage allows storage in the session.


예를 들어 성과 이름을 저장하려면 아래와 같이 하시면 됩니다.


Permanent storage


localStorage.lname = "Sarrion";

localStorage.fname = "Eric";


Session storage


sessionStorage.lname = "Sarrion";

sessionStorage.fname = "Eric";


Using a database


위에서 본 Permanent storage 와 temporary storage 는 SQL 을 사용하는 데이터베이스에서 제공하는 많은 기능들을 제공하지는 않습니다.

이런 데이터베이스를 이용하려면 HTML5 에서 제공하는 SQL 데이터베이스를 자바스크립트를 사용해서 활용하시면 됩니다.


Creating the database



첫번째로 데이터베이스에 대한 access 를 생성합니다. 이게 첫번째로 실행될 경우 그 데이터베이스는 빈 DB 가 되겠죠.


Create access to the database


var db = openDatabase ("Test", "1.0", "Test", 65535);



위 소스에서는 string size 를 65,535 bytes 로 지정했습니다.


Using the database


일단 데이터베이스가 생성됐으면 이제 사용하시기만 하면 됩니다.


  • Creating tables,

  • Inserting data into tables,

  • Retrieving data from the tables,

  • Deleting data,

  • Eventually deleting tables.


데이터 관리하는 방법은 간단합니다. db object 가 recover 됐다면 이제 SQL 명령문을 사용하시면 됩니다.


Using the database


var db = openDatabase ("Test", "1.0", "Test", 65535);

db.transaction (function (transaction) 

{

  var sql = SQL query;

  transaction.executeSql (sql, [parameters] / undefined, 

  function ()

  

    // JavaScript code to execute if the query was successful

    // ...

  }, 

  function ()

  

    // JavaScript code to execute if the query failed

    // ...

  } );

});



parameters들은 배열 형태이고 SQL query 안에서 "?" 로 replace 됩니다. 이 파라미터들은 "?" 가 없으면 사용할 필요가 없습니다.


이어지는 두 함수들옵션인데요 둘 중 하나가 indicated 되지 않았다면 undefined replace 되어야 합니다. 첫번째 함수는 트랜잭션이 성공했을 때 실행되고 두번째 함수는 실패 했을 때 실행됩니다.


두번째 함수의 return 은 중요한 의미가 있죠. request 가 실패했다는 의미이니까요. 이렇게 request 가 실패 했을 때 그 트랜잭션의 request 들을 rollback 하는 부분을 구현해야 합니다. 실패 했을 때 제대로 rollback 하기 위해 해당 함수의 마지막에 true return 하면 됩니다. 그렇지 않다면 성공했다고 간주하게 됩니다.


Example of using a database


customers table로 데이터베이스를 관리할 겁니다. 그러려면 테이블을 생성하고 그 안에 내용을 넣고 지우고 보여주고 하는 기능들을 구현해야죠.


Managing a database of clients locally


<!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 data-role=page id=home>

  <div data-role=header>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <a href=# data-role=button id=create> Create customers table </a>

    <a href=# data-role=button id=remove> Delete customers table </a>

    <span> Last name </span>

    <input type=text id=lname>

    <span> First name </span>

    <input type=text id=fname>

    <a href=# data-role=button id=insert> Insert the customer </a>

    <a href=# data-role=button id=list> List customers </a>

  </div>

</div>


<div data-role=page id=win2 data-add-back-btn=true>

  <div data-role=header>

    <h1>List of customers</h1>

  </div>


  <div data-role=content>

  </div>

</div>


</body>

</html>


<script>


var db = openDatabase ("Test", "1.0", "Test", 65535);


$("#create").bind ("click", function (event)

{

  db.transaction (function (transaction) 

  {

    var sql = "CREATE TABLE customers " +

        " (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +

        "lname VARCHAR(100) NOT NULL, " + 

        "fname VARCHAR(100) NOT NULL)"

    transaction.executeSql (sql, undefined, function ()

    

      alert ("Table created");

    }, error);

  });

});


$("#remove").bind ("click", function (event)

{

  if (!confirm ("Delete table?", "")) return;;

  db.transaction (function (transaction) 

  {

    var sql = "DROP TABLE customers";

    transaction.executeSql (sql, undefined, ok, error);

  });

});


$("#insert").bind ("click", function (event)

{

  var lname = $("#lname").val ();

  var fname = $("#fname").val ();

  

  db.transaction (function (transaction) 

  {

    var sql = "INSERT INTO customers (lname, fname) VALUES (?, ?)";

    transaction.executeSql (sql, [lname, fname], function ()

    

      alert ("Customer inserted");

    }, error);

  });

});


$("#list").bind ("click", function (event)

{

  db.transaction (function (transaction) 

  {

    var sql = "SELECT * FROM customers";

    transaction.executeSql (sql, undefined, 

    function (transaction, result)

    {

      var html = "<ul>";

      if (result.rows.length)

      {

        for (var i = 0; i < result.rows.length; i++) 

        {

          var row = result.rows.item (i);

          var lname = row.lname;

          var fname = row.fname;

          html += "<li>" + lname + "&nbsp;" + fname + "</li>";

        }

      }

      else

      {

        html += "<li> No customer </li>";

      }

      

      html += "</ul>";

      

      $("#win2").unbind ().bind ("pagebeforeshow", function ()

      {

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

        $content.html (html);

        var $ul = $content.find ("ul");

        $ul.listview ();

      });

      

      $.mobile.changePage ($("#win2"));

      

    }, error);

  });

});


function ok ()

{

}


function error (transaction, err) 

{

  alert ("DB error : " + err.message);

  return false;

}


</script>


tistory573_01.html


쿼리가 데이터베이스에서 기록들을 return 할 경우 자바스크립트 함수는 ResultSet object 에 해당하는 result parameter를 성공적으로 수행했을 때 실행됩니다. 이 쿼리에 의해 생성된 자료들을 담고 있는 rows property 가 생기게 됩니다.


Access to the records returned by a SELECT


for (var i = 0; i < result.rows.length; i++) 

{

  var row = result.rows.item (i);

  var lname = row.lname;

  var fname = row.fname;

  html += "<li>" + lname + "&nbsp;" + fname + "</li>";

}


이 프로그램에서 흥미로운 부분은 리스트를 display 하는 부분 입니다. 화면의 content 로 insert 하기 위해 <ul> list HTML 코드를 사용했습니다. 리스트를 listview () method를 사용해서 listview component 로 변환하는 것은 화면에 들어갈 리스트가 이미 생성돼 있을 때에만 가능합니다.
pagebeforeshow event 가 그 당시 화면이 생성돼 있는지 여부를 체크할 수 있도록 해 줍니다.


unbind () method가 bind () method 이 전에 사용된 점을 유념하세요. bind () method를 성공적으로 call 하면 perform 해야할 일들이 쌓이게 됩니다. (만약 리스트가 여러번 display 되야 하는 경우에요.) unbind ()
method를 call 하면 이전에 add 됐던 모든 이벤트 핸들러들을 remove 합니다.  그러니까 마지막에 우리가 bind ()로 추가한 것만 남게 되죠.


이 소스를 실행시키면 아래와 같은 화면을 보실 수가 있을 겁니다.





customers table 생성의 다른 action 들은 이 테이블이 아직 생성되지 않았을 경우 에러 메세지를 보여줄 겁니다.  일단 생성되면 다른 action들을 취할 수 있습니다. 두개의 클라이언트를 생성하고 list 해 보죠. 해당 버튼을 잘 눌러서요.



Improving the program (continued)


위의 프로그램을 조금 더 개선 시키겠습니다. 리스트에서 한개의 client 를 remove 할 수 있도록요. 이것을 하려면 리스트 아이템에 swipe movement (right)을 감지할 수 있도록 해야 할 겁니다. 오른쪽으로 문지르면 그 아이템이 리스트에서 지워질겁니다. 더불어서 데이터베이스에서도 그 정보가 지워질 거구요.


아래에 이를 위한 구문이 있습니다.


Allow the removal of an item in the list


$("#list").bind ("click", function (event)

{

  db.transaction (function (transaction) 

  {

    var sql = "SELECT * FROM customers";

    transaction.executeSql (sql, undefined, 

    function (transaction, result)

    {

      var html = "<ul>";

      if (result.rows.length)

      {

        for (var i = 0; i < result.rows.length; i++) 

        {

          var row = result.rows.item (i);

          var lname = row.lname;

          var fname = row.fname;

          var id = row.id;

          html += "<li data-icon=false " + "id=" + id + ">";

          html +=   "<a href=#>";

          html +=      lname + "&nbsp;" + fname; 

          html +=   "</a>"; 

          html += "</li>";

        }

      }

      else

      {

        html += "<li> No customer </li>";

      }

      

      html += "</ul>";

      

      $("#win2").unbind ().bind ("pagebeforeshow", function ()

      {

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

        $content.html (html);

        var $ul = $content.find ("ul");

        $ul.listview ();

        

        $("li").bind ("swiperight", function (event)

        {

          var id = $(this).attr ("id");

          if (!id) return;

          

          $(this).remove ();

          

          db.transaction (function (transaction) 

          {

            var sql = "DELETE FROM customers WHERE id=?";

            transaction.executeSql (sql, [id], function ()

            

              alert ("Customer deleted");

            }, error);

          });

        });        

      });

      

      $.mobile.changePage ($("#win2"));

      

    }, error);

  });

});


<li> list item 은 리스트 아이템에 <a> element 가 삽입되면서 높이가 더 커질 겁니다. 리스트 아이템의 id attribute 는 데이터베이스 안에 있는 client 의 identifier 입니다. 이것으로 해당 client 가 어느 리스트 아이템과 연관된 건지 알수 있습니다. 그래서 해당 리스트 아이템을 지울 때 데이터베이스의 해당 데이터도 지울 수 있는 거죠.


그리고 이제 각 리스트 아이템별로 swiperight event handler 를 연결 시킵니다. 이 이벤트가 발생하면 display 된 해당 리스트 아이템이 remove 될 겁니다. 그리고 나서 데이터베이스의 해당 id 를 가지고 있는 데이터가 지워질 겁니다.



반응형

툴바 만드는 예제들

2012. 12. 28. 05:33 | Posted by 솔웅


반응형
Examples of manipulation of toolbars



Manage a tab system in a navigation bar


navigation bar의 버튼을 클릭할 때마다 다른 content 를 보여주려고 합니다. 물론 page 이동 없이 각 버튼이 선택될 따마다 해당 page 에서 content 만 바꿔서 display 할 겁니다.


Manage tabs in the navigation bar


<!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 data-role=page id=home>

  <div data-role=header data-position=fixed>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Window content </p>

  </div>

  

  <div data-role=footer data-position=fixed>

    <div data-role=navbar>

      <ul>

        <li id=menu1><a href=#>Menu 1</a></li>

        <li id=menu2><a href=#>Menu 2</a></li>

        <li id=menu3><a href=#>Menu 3</a></li>

      </ul>

    </div>

  </div>

</div>


</body>

</html>


<script>


$("li").bind ("vclick", function (event)

{

  var id = this.id;

  if (id == "menu1") $("#home div:jqmData(role=content)")

                        .html ("<p> Content menu 1 </p>");

  else if (id == "menu2") $("#home div:jqmData(role=content)")

                        .html ("<p> Content menu 2 </p>");

  else if (id == "menu3") $("#home div:jqmData(role=content)")

                        .html ("<p> Content menu 3 </p>");

});


</script>

tistory570_01.html



navigation bar에 있는 버튼을 클릭할 때마다 화면의 contents 가 바뀝니다. 그리고 처음 화면이 뜰 때는 아무 버튼도 selected 돼 있지 않은 상태죠. 화면이 뜬 후 버튼을 클릭할 때마다 content를 바꾸는 로직이 실행 됩니다.


Simulate a click on the first button


$("div:jqmData(role=navbar)").bind ("navbarcreate", function (event)

{

  $("li#menu1 a.ui-btn").trigger ("vclick");

});


이 코드는 navigation bar 가 생성될 때  (navbarcreate event) 실행됩니다. 그 이전에는 ui-btn class의 <a> link는 존재하지가 않습니다. 왜냐하면 아직 jQuery Mobile 에 의해서 HTML 코드가 변환되지 않았으니까요.


Manage the content of the tabs by Ajax


HTML 에 있는 자바스크립트 코드로 tab들의 contents들을 수정하는 대신 Ajax를 통해서 서버로부터 HTML 코드를 받아 오는 것을 구현하겠습니다.


Retrieve the contents of the tabs by Ajax


<!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 data-role=page id=home>

  <div data-role=header data-position=fixed>

    <h1>Home</h1>

  </div>


  <div data-role=content>

    <p> Window content </p>

  </div>

  

  <div data-role=footer data-position=fixed>

    <div data-role=navbar>

      <ul>

        <li id=menu1><a href=#>Menu 1</a></li>

        <li id=menu2><a href=#>Menu 2</a></li>

        <li id=menu3><a href=#>Menu 3</a></li>

      </ul>

    </div>

  </div>

</div>


</body>

</html>


<script>


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

{

  $("li#menu1 a.ui-btn").trigger ("vclick");

});


$("li").bind ("vclick", function (event)

{

  var id = this.id;

  $.ajax (

  

    url : "action.php", 

    data : { menu : id },

    complete : function (xhr, result)

    {

      if (result != "success") return;

      var response = xhr.responseText;

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

    }

  });  

});


</script>


action.php file


<?
$menu = $_REQUEST["menu"];

$html = "";
if ($menu == "menu1")
  $html .=   "<p> Content menu 1 </p>";
else if ($menu == "menu2")
  $html .=   "<p> Content menu 2 </p>";
else if ($menu == "menu3")
  $html .=   "<p> Content menu 3 </p>";
  
echo utf8_encode ($html);
?>

action30.php

tistory570_02.html




Methods managing fixed toolbars



data-position="fixed" attribute를 사용한 fixed type 의 toolbar 들을 관리하기 위해 jQuery Mobile은 아래 메소드들을 제공합니다.


Methods managing fixed toolbars


Method

Signification

$(selector)
.fixHeaderFooter ();

Search toolbars with the data-position = "fixed" attribute in the descendants of the elements represented by the specified selector, and transforms them into fixed toolbars. This allows to dynamically create these toolbars (see an earlier example in this chapter)

$.mobile
.fixedToolbars
.setTouchToggleEnabled (enable)

Enables (if enable is true) or disables (if enable is false) the ability to display and hide fixed toolbars by clicking in the window. By default, clicking in the window displays or hides fixed toolbars present in it. To disable this default, use $.mobile
.fixedToolbars
.setTouchToggleEnabled (false).

$.mobile
.fixedToolbars
.show (immediately)

Allows you to reposition the fixed toolbars in the window, if the modification of the contents of the window has changed their position. The immediately parameter indicates whether repositioning occurs immediately (if true) or if it is done by a fade effect (if false, the default).

$.mobile
.fixedToolbars
.hide ()

Allows to hide the fixed toolbars in the window. They are redisplayed at the next click in the window (unless this function has been disabled by $.mobile
.fixedToolbars
.setTouchToggleEnabled (false).





반응형