riot.jsの勉強1日目ですが、カスタムタグと外部スクリプトの間でやりとりする方法がパッと見つからなかったのでメモしておきます。
カスタムタグの関数を外部から呼び出す方法
以下のようなカスタムタグitemがある場合
<item>
<button onclick='{add}'>add</button>
<table>
<tr each='{item_list}'>
<th>{ name }</th>
</tr>
</table>
this.item_list = [];
this.add = function(e) {
this.item_list.push({ name: '要素' + this.item_list.length, value: this.item_list.length});
}
this.addItem = function() {
this.item_list.push({ name: '要素' + this.item_list.length, value: this.item_list.length})
console.log(this)
this.update();
}
</item>
カスタムタグitemの関数addItemは以下のように呼び出せます。
riot.mountの返り値のオブジェクトがカスタムタグのthisと同じ役割を果たします。
カスタムタグは複数記述できるので、返り値はオブジェクトの配列であることに気をつけて下さい。
<script>
var item = riot.mount('item')
item[0].addItem();
</script>
全体のソースは以下のようになります。
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script src='https://cdn.jsdelivr.net/riot/2.3/riot+compiler.min.js'></script>
<title>RiotJS Test</title>
</head>
<body>
<item></item>
<script type="riot/tag">
<item>
<button onclick='{add}'>add</button>
<table>
<tr each='{item_list}'>
<th>{ name }</th>
</tr>
</table>
this.item_list = [];
this.add = function(e) {
this.item_list.push({ name: '要素' + this.item_list.length, value: this.item_list.length});
}
this.addItem = function() {
this.item_list.push({ name: '要素' + this.item_list.length, value: this.item_list.length})
console.log(this)
this.update();
}
</item>
</script>
<script>
var item = riot.mount('item')[0]
item.addItem();
</script>
</body>
</html>
外部の関数をカスタムタグから呼び出す方法
外部の関数は、通常の呼び出し方法で呼び出せます。
つまり、以下のような関数があった場合
<script>
function globalFunc(text) {
console.log(text);
}
</script>
カスタムタブの内部からも以下のコードで呼び出せます。
globalFunc('test');