はじめに
Web Componentsがアツいらしいので、今更ながらPolymerを使ってみました。
今回は例として、Twitterのつぶやくボタンを作ってみます。
Web Components
去年とか一昨年とか流行ったので知っていると思いますが、おさらいから。
特徴
置くだけ簡単再利用。
ボタンとかUI部品のHTML,CSS,JSのコードを再利用出来るようにする(コンポーネント)、Webの標準技術で!
あと、CSSがスコープを持つのであそこを変更したらこっちが崩れたみたいなことが無くなる。
機能
- Custom Elements
- HTML Imports
- template element
- Shadow DOM
こちらの記事に詳しくまとまっていました。
Web Componentsの構成要素まとめ(基本編)
Polymer
Web Componentsをベースとしたライブラリです。
Web ComponentsといえばPolymerらしいので、使ってみます。
ちなみに、v2がそろそろ出そうなので、この記事も役に立たなくなるかもしれません。
準備
を参考にpolymer-cli
を使ってプロジェクトを作成します。
$ polymer init
? Which starter template would you like to use? (Use arrow keys)
❯ element - A blank element template
application - A blank application template
shop - The "Shop" Progressive Web App demo
starter-kit - A starter application template, with navigation and "PRPL pattern" loading
info: Running template element...
? Element name tweet-button
? Brief description of the element
今回は部品を作りたいので、element
を選択しました。
bowerのライブラリがインストールされると、下記のファイルが作られます。
- tweet-button.html - 本体
- demo/index.html - 動作確認用のhtml
とりあえず、起動します。
$ polymer serve
Starting Polyserve...
serving on port: 8080
from root: /Users/k_hatano/tmp/polymer
Files in this directory are available under the following URLs
applications: http://localhost:8080
reusable components: http://localhost:8080/components/tweet-button/
http://localhost:8080/demo/ にアクセスすると、スクリプトが404のエラーになっていると思います。
bower_components
の下を読むようにパスを適宜変えてあげましょう・・・。
Helloされたものが表示されたと思います。
実装
プログラム
こんな感じになりました。
<link rel="import" href="bower_components/polymer/polymer.html">
<!--
`tweet-button`
@demo demo/index.html
-->
<dom-module id="tweet-button">
<template>
<a class="twitter-share-button"
href="https://twitter.com/share"
data-size$="[[size]]"
data-text$="[[text]]"
data-url$="[[url]]"
data-hashtags$="[[hashTags]]"
data-via$="[[via]]"
data-related$="[[related]]"
data-lang$="[[lang]]"
data-dnt$="[[dnt]]">
Tweet
</a>
</template>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<script>
Polymer({
is: 'tweet-button',
properties: {
size: {
type: String
},
text: {
type: String
},
url: {
type: String
},
hashTags: {
type: String
},
via: {
type: String
},
related: {
type: String
},
lang: {
type: String
},
dnt: {
type: Boolean
}
}
});
</script>
</dom-module>
使い方
<tweet-button url="http://example.com" text="foo" via="twitterdev" hash-tags="example,demo"></tweet-button>
ハマりどころ
- bindの書き方
attributeにbindするときは$
を付ける。
<a href$="{{hostProperty}}">
カスタムのpropertyのときはそのまま。
<my-element my-property="{{hostProperty}}">
-
{{}}
と[[]]
の違い
{{}}
は双方向、[[]]
は単一方向のバインディング。
まとめ
tweetするだけの簡単な感じでしたが、なんとなくPolymerの使い方が見えた気がします。
ただ、polymer-cli
はまだこなれていないっぽいのですね。
Web Components 2016 & Polymer v2
上記の資料によると、Web Component界隈はいろいろあったそうなので
v2が出たら本格的にPolymerやWeb Componentそのものの学習をしてみようかと思います。