Polymerのcore-ajaxの使い方。
まずは、index.html
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./bower_components/webcomponentsjs/webcomponents.js"></script>
<link rel="import" href="my-topics.html">
</head>
<body fullbleed vertical layout unresolved>
<my-topics></my-topics>
</body>
</html>
my-topics
というCustom Elementに実際の処理を書く。JSONで、とあるサーバからデータを取得する、という想定。本当はJSONPで取りたかったんだけど、それは次回までの課題で...
my-topics.html
<polymer-element name="my-topics" attributes="">
<link rel="import" href="bower_components/core-ajax/core-ajax.html">
<template>
<core-ajax auto url="http://url.to.api/"
handleAs="json"
on-core-response="{{handleResponse}}"></core-ajax>
<table id="topics">
<tr template repeat="{{topic in topics}}">
<td><a href="{{topic.uri}}">{{topic.title}}</a></td>
</tr>
</table>
</template>
<script>
Polymer('my-topics',{
handleResponse: function(ev,res){
this.topics = res.response;
}
});
</script>
</polymer-element>
core-ajax
のon-core-response
は、ajaxで取得でき時に呼ばれ関数を指定する。実際のレスポンスは、指定した関数の第2引数に格納される。実際の第1引数(ev)と第2引数(res)には次のような値が入る。
>ev
CustomEvent {detail: Object, clipboardData: undefined, path: NodeList[12], cancelBubble: false, returnValue: true…}
>res
Object {response: Array[398], xhr: XMLHttpRequest}