블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2015. 1. 3. 19:25 Angular/Prototyping

구글 폴리머기반으로 자신만의 Web Components 를 만들어 보자. 아주 초간단 웹 컴포넌트이지만 기반 컴포넌트를 설치하고 어떻게 구동되는지 손으로 익혀본다. 




설치하기 


  - 폴러머를 시작하기 위해 zip파일을 받을 수 있지만 클라이언트 컴포넌트 의존관리 툴이 바우어(Bower)를 사용한다. 

     바우어는 노드(Node.js)기반위에 돌ㄹ아가기 때문에 노드를 설치하고 바우어도 설치한다. 

  - 바우어를 통해 프로젝트를 초기화 해보자. bower init 후에 그냥 끝날 때가지 엔터를 친다. bower.json 환경파일이 생성된다. 

$ mkdir tutorial && cd tutorial

$ bower init 


  - 폴리머를 설치한다. polymer.js 는 Web Components를 지원하기 위한 polyfill 파일인 webcomponents.js 파일도 포함한다. 

    + polyfill은 Web Components 스팩을 지원하지 않는 브라우져에서도 Web Components를 사용할 수 있도록 해주는 파일이다. 

       따라서 과거 브라우져는 webcomponents.js (과거는 platform.js였음) 파일을 추가해야 한다. 

     + Chrome 36+ 이상 버전은 Web Components 스팩이 구현되어 있기 때문에 polyfill 파일이 필요없다. 

$ bower install --save Polymer/polymer




처음 만들어 보는 웹 컴포넌트 


  - 웹컴포넌트를 만든 후 html안에서 사용한다. 

  - 먼저 폴리머 웹 컴포넌트를 정의한다. 

    + 폴리머 엘러먼트를 사용하기 위해 polymer.html을 추가한다. 

    + 사용자 정의 웹컴포넌트 이름은 hi-dowon이다. 구분은 "-" 을 꼭 사용한다. 

    + html에서 사용할 때 public으로 노출 시킬 attribute로 name을 지정한다. 

    + <template>와 <script>에서 상호 작용한다. 스크립트 태그에 지정한 값이 template 쪽으로 {{}} 사용해 양방향 바인딩 된다. 

tutorial> mkdir elements && cd elements

tutorial/elements> vi hi-dowon.html 


// hi-dowon.html 내용 

<link rel="import" href="../bower_components/polymer/polymer.html">


<polymer-element name="hi-dowon" attributes="name">

  <template>

    <span> This is <b>hi-<span style="color: {{color}}">{{owner}}</span></b> tag <br>

    <span> And hi {{name}}</span><br>

    <input id="message" value="{{name}}">

    <button on-click="{{setFocus}}">Set Focus in name input</button>

  </template>

  <script>

    Polymer({

      owner: 'Dowon',

      color: 'red',

      name: 'youngsik',

      setFocus: function() {

        this.$.message.focus();

      }

    })

  </script>

</polymer-element>


  - 이제 elements/hi-dowon.html 파일을 사용하는 index.html 파일을 작성한다. 

    + 웹 컴포넌트는 HTML imported를 통해 사용하고자 하는 웹컴포넌트를 조합(Composition)해 확장(Scale-out)하는 방식이다. 

    + 모던 브라우져가 아닌 구버전의 브라우져에서 웹컴포넌트 스펙지원을 위해 polyfill파일인 webcomponents.js 파일추가한다. 

       Chrome 36+ 이상 버전은 polyfill 설정이 필요없다. 

<!DOCTYPE html>

<html>

    <head>

        <script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>

        <link rel="import" href="./elements/hi-dowon.html">

    </head>

    <body>

        <hi-dowon name="ok"></hi-dowon>

    </body>

</html>


  - 결과 수행

    + 파이썬의 심플 서버를 뛰어서 호출해 본다. 

tutorial> python -m SimpleHTTPServer 8000


// 결과 화면 : 버튼을 클릭하면 포커스이동 


  - 폴리머의 레이어는 3계층으로 나뉜다 

    1) Web Components : Web Components 스팩을 지원하지 않는 브라우져를 위한 web components polyfill 레이어 

    2) Polymer 라이브러리 : 사용자 정의 엘러먼트(Custom element)를 위한 선언적 신택스를 제공

    3) Elements :Core 와 Paper element와 같이 기정의된 웹 컴포넌트 제공. 




1. Polymer에서 Custom Elements


  - Custom Element is True Element. 사용자 정의 엘러먼트를 사용하는 이유를 보자.

  • Reduce the amount of code you have to write. : 누군가 만들어 놓은 엘러먼트가 있다면 Don't invent한다. 
  • Express the function of the code. : 
  • Encapsulate internal details. : 코드 내부를 캡슐화 할 수 있다 
  • Implement APIs per element type. : 엘러먼트별 API가 있고 애트리뷰트로 접근한다. 
  • Increase productivity by letting you reuse elements. : 엘러먼트를 조합해서 생산성을 높일 수 있다. 
  • Use inheritance to create element tags based on other tags. : extends 키워들 통해 custom element를 확장할 수 잇다


  - 웹 컴포넌트의 Custom Element는 다음과 같이 작성을 해야하지만 폴리머를 쓰면 단순히 <polymer-element> 태그를 사용하면 끝!

    + Customer Element 명칭을 지을 땐 반드시 "-"이 있어야 한다. (polymer element 선언 참조)

// 코딩 

var myTag = document.registerElement('my-tag');


// 선언적 태깅 

<polymer-element name="my-tag">

  <template> 

    <div> hello dowon </div> 

  </template>

  <script>

     Polmer();

  </script>

</polymer-element>


  - extends 키워드를 통해 기존 엘러먼트를 확장할수 있고, 부모의 메소드와 속성을 자식 엘러먼트가 상속받는다. 

    또한 오버라이딩도 가능한다. 

  - 엘러먼트 종류로 UI 렌더링되는 엘러먼트와 No-UI 엘러먼트를 만들 수 있다. 예로 <core-ajax>은 XHR 요청을 마크업으로 할 수 있게 한다. 

<core-ajax url="http://gdata.youtube.com/feeds/api/videos/" auto params='{"alt":"json", "q":"chrome"}' handleAs="json"></core-ajax>

<script>

  var ajax = document.querySelector('core-ajax');

  ajax.addEventListener('core-response', function(e) {

    console.log(this.response);

  });

</script>




2. Polymer에서 Shadow DOM


  - 프로그램적으로 Shadow DOM을 하려면 createShadowRoot를 넣어야 하지만 Polymer에서는 <template> 태그를 사용한다. 

    + <span> <content> <footer>는 다른 커스텀 엘러먼트안에 있을 때 완전 캡슐화되어 숨겨진다는 것을 명심하자. 

<polymer-element name="my-custom-element" noscript>

  <template>

    <span>People say: </span>

      <content select="qq"></content> 

    <footer>sometimes</footer>

  </template>

</polymer-element>

  

  - DOM은 3가지가 있다. Light DOM, Shadow DOM, Composed DOM

     + Light DOM : 하기와 같이 my-custom-element 안에 <qq> Hi dowon </qq>로 포함된 DOM 이다. innerHTML로 접근이 가능하다.  

<my-custom-element>

  <qq> Hi dowon </qq>

</my-custom-element>


    + Shadow DOM : <polymer-element> 태그 안에 <template> ... </template> 태그안에 정의된 DOM 이다. 

       DevTools에서는 #docuement-fragment로 표기되고 사용자에게 숨겨져있고, <my-custom-element> 자식노드로 접근이 안된다. 


    + Composed (rendered) DOM : 실제 브라우져에 렌더링되는 DOM 이다. 

       light DOM이 shadow DOM에 포함되어 조합된 DOM이 보여진다. (이것은 마치 AngluarJS의 Directive에서 transclude와 유사하다)

<my-custom-element>

  <span>People say: <qq>Hi dowon</qq></span>

  <footer>sometimes</footer>

</my-custom-element>




3. Polymer에서 HTML imports 


  - <link> 태그를 사용해 HTML 도큐먼트를 재사용하면 된다. 

<link rel="import" href="my-custom-element.html">




4. Polymer에서 Web Animations


  - Web Animation 관련한 CSS Transitions, CSS Animations, SVG Animations /SMIL 스팩이 있다. 

    + 구현체

    + 아직은 복잡한 것을 표현하기에 부족함이 존재

  - 애니메이션 cost를 줄이고, animation 스팩끼리 상호작용할 수 있고, 스팩 작성자나 브라우져 벤더가 한 곳에서 사용할 수 있게하자.

  - Web Animations 모델은 웹에 애니메이션 컨텐트를 엔진에 묘사하는 것이다. 

     엔진은 CSS Transitions, CSS Animations, SVG Animations 를 지원한다. 

    + 자바스크립트 API를 통해 애니메이션을 정의 

    + Animation 오브젝트를 사용 그외 AnimationEffect, AnimationGroup, AnimationSequence 오브젝트를 사용한다. 




5. Polyfill로서 Web Components


  - web components 기술이 모든 브라우져에 구현되어 있지 않기 때문에 webcomponents.js polyfill 파일이 필요함 

  - webcomponents.js 는 다음의 라이브러리를 포함하고 있다. 

  • Web Components:

  • Dependencies required by the Web Components polyfills:


  - 설치는 바우어로 하고 웹 컴포넌트를 사용하려는 HTML에 <script> 태그로 포함시킨다. 

$ bower install --save webcomponentsjs


// html

<script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>




<참조> 

  

  - Polymer 10 minutes

  - Understanding web components

  - 구글 폴리머 튜토리얼


posted by 윤영식