LoginSignup
16
13

More than 5 years have passed since last update.

Mithril.js 試してみた(2) サーバーからデータを取得する m.request()

Last updated at Posted at 2015-08-26

今度は、Mithril.js でサーバーからデータを取得するだけのサンプルです。

まぁ、jQuery$.ajax() とか $.get()$.post() 相当ですね。

前回までの記事:
Mithril.js 試してみた(1) todo アプリを作り始める所まで - Qiita
Mithril.js 試してみた(2) サーバーからデータを取得する m.request() - Qiita ⇒ この記事
Mithril.js 試してみた(3) console.logの様に画面に表示してみる - Qiita
Mithril.js 試してみた(4) todo アプリのフロント側まで - Qiita
Mithril.js 試してみた(5) Excelの様な表計算アプリを3時間で作る m.component() - Qiita

サーバーからデータを取得するには m.request() を使うと良い。

m.request() の結果は、m.prop() 相当で、なおかつ、Promise だ。

なので、そのまま、view の中で関数呼び値を取得して、表示できる。

画面の更新タイミングは、結果が取得できたら m.redraw() が呼ばれる感じだ。

Promise なので、then() もできる。

以下の様な画面になるサンプル・コードを示す。

qiita-mithril-links.png

サンプル・コード

links.html
<!DOCTYPE html>
<meta charset="UTF-8">
<title>links - Mithril.js</title>

<script src="mithril.min.js"></script>
<!--[if IE]><script src="es5-shim.min.js"></script><![endif]-->

<body>
<div id="$linksElement"></div>
</body>

<script>

// コンポーネント定義
var linksComponent = {
    // コントローラ
    controller: function () {
        // データをサーバーから取得する
        this.list = m.request({method: 'GET', url: 'links.json', initialValue: []});
    },
    // ビュー
    view: function (ctrl) {
        return m('ul',
            ctrl.list().map(function (item) {
                return m('li', [m('a', {href: item.url}, item.title)]);
            })
        );
    }
};

m.mount($linksElement, linksComponent);

</script>

サンプル・データ

links.json
[
  {"title": "qiita.com", "url": "http://qiita.com"},
  {"title": "google",    "url": "http://www.google.co.jp"},
  {"title": "facebook",  "url": "http://www.facebook.com"}
]

まだデータ取得が完了していない時に、もし再描画される場合などには、値が無くてエラーになる事があるので、initialValue を使うと、そういうエラーも回避できるよ。

もちろん、データをサーバーにあげるときも、m.request() を呼べばできるよ。
m.request() は、JSONPもサポートしている。

16
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13