5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

riot.jsでカスタムタグの関数と外部関数の相互呼び出し方法

Posted at

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');
5
7
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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?