あわせてこちらもご覧ください。
JavaScript軽量フレームワークxattoのcontextについて
xattoとは
https://github.com/atomita/xatto
JavaScript製の軽量フレームワークです。
JavaScriptフレームワークの有名どころでいうと
- Angular
- React
- Vue.js
などがありますが、
この中でいうとReactに近い感じです。
とりあえず動かして見よう
ちなみに私の環境は以下です。
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.4
BuildVersion: ...
$ node -v
v10.1.0
$ npm -v
6.7.0
デモがあるのでそれを動かしてみましょう
https://github.com/atomita/xatto-starter-kit
www $ git clone git@github.com:atomita/xatto-starter-kit.git
www $ cd xatto-starter-kit
www/xatto-starter-kit $ yarn
www/xatto-starter-kit $ yarn run dev
...
...
Server running at http://localhost:58080
✨ Built in 1.51s.
となれば成功です。ブラウザから http://localhost:58080
にアクセスしてみるとカウンターのデモが表示されていて
[-]や[+]をクリックするとカウンターの数字を増減できます。
コードを見てみよう
src/index.html
特に何も書くことはないですがw
1xattoが動作する”入れ物”を用意しています。(あとでdocument.getElementById('app')
を指定しています。)
2./boot.js
を読み込んでいますが、結局boot.js
経由でapp.jsx
を読み込む感じになっています。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Starter kit for xatto</title>
<meta
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
name="viewport"
>
</head>
<body>
<div id="app"></div> <!-- 1 -->
<script src="./boot.js"></script> <!-- 2 -->
</body>
</html>
src/app.jsx
5でアプリの初期化をしていますid="app"
のhtml要素にview
をレンダリング的な感じでしょうか。
このアプリのパラメーターとして、{counters: [{ count: 0 }, { count: 10 }]}
を渡していて
2、3でパラメーターの一部をコンポーネントに渡しています。
import { x, atto } from 'xatto';
import { Counter } from './components/Counter';
const view = ({ xa: { context }, ...attrs }, children) => ( // 1
<div>
<Counter xa={{ slice: 'counters.0' }} /> {/*2*/}
<Counter xa={{ slice: 'counters.1' }} /> {/*3*/}
<h1>{context.counters.reduce((acc, v) => acc + v.count, 0)}</h1> {/*4*/}
</div>
);
atto(view, document.getElementById('app'))({ // 5
counters: [{ count: 0 }, { count: 10 }],
});
src/components/Counter/index.js
上記で使っているCounter
コンポーネントの中身ですが、
上記の2の例で言うとattrs.xa.context
に{ count: 0 }
がセットされています。
ここでは受け取った(attrs, children)
をそのままCounterView(attrs, children)
に渡していますが、パラメーターの値を付け足したり、書き換えたり、操作したい時にはviewに渡す前のここでやります。
import { CounterView } from './view';
import './view.styl';
export const Counter = (attrs, children) => CounterView(attrs, children);
src/components/Counter/view.jsx
ここは見たまんまと言いますか、
特に補足はないですw
import { x } from 'xatto';
const down = context => ({ count: context.count - 1 });
const up = context => ({ count: context.count + 1 });
export const CounterView = ({ xa: { context }, ...attrs }, children) => (
<div class="c-counter">
<h1>{context.count}</h1>
<button onclick={down}>-</button>
<button onclick={up}>+</button>
</div>
);