Webページに Tree 描画させるのに、Wicket が提供しているものは、Java Object で要素&ツリー体系を作らなくてはならず、
これは手間もかかって非常に辛い。巨大なツリーで children が大量の時、結果表示スピードも心配だ。
だから Wicket の Tree 機能は使ってない。
JSON → ツリー描画 させる jQuery が世の中にはたくさんある。MIT ライセンスでそこそこ簡単に使えそうなもので
jsTree : https://www.jstree.com/
GitHub - vakata/jstree: jquery tree plugin
この jsTree でツリーのノードをクリック=選択した時の捕捉は、
select_node.jstree か、changed.jstree イベントを捕捉する
サンプルで書くと、、
<div id="tree1" class="demo"></div>
select_node.jstree と、changed.jstree を on でバインド
$.jstree.defaults.core.themes.variant = "large"; $.jstree.defaults.core.themes.responsive = true; $('#tree1').jstree({ 'core':{ 'data':[ { "id":1, "text":"Root node", "children":[ { "id":2, "text":"Child node 1", "children":[ { "id":3, "text":"aaa" }, { "id":4, "text":"bbb" } ], }, { "id":5, "text":"Child node 2" } ] }, { "id":6, "text":"Root node2", "children":[ { "id":7, "text":"Child node 1" }, { "id":8, "text":"Child node 2" } ] } ] }}) .on("select_node.jstree", function(e, data){ console.log("selected is : id =" + data.node.id +" "+ data.node.text); }) .on("changed.jstree", function(e, data){ console.log("changed is : id =" + data.node.id +" "+ data.node.text); });
もう1つ捕捉の書き方、jQuery の原始的な捕捉と書き方で、、
var tree = $('#tree1').jstree({ 'core':{ 'data':[ { "id":1, "text":"Root node", "children":[ { "id":2, "text":"Child node 1", "children":[ { "id":3, "text":"aaa" }, { "id":4, "text":"bbb" } ], }, { "id":5, "text":"Child node 2" } ] }, { "id":6, "text":"Root node2", "children":[ { "id":7, "text":"Child node 1" }, { "id":8, "text":"Child node 2" } ] } ] }}); tree.on('click', '.jstree-anchor', function(e){ var id = $(this).parent().attr('id'); var text = $(this)[0].text; console.log("id = " + id + " text = " + text); });
この書き方、$(this).parent().attr('id') で、IDの参照
$(this)[0].text で、ノードのテキストを参照
をマスタしておいた方が、ダブルクリック等の他のイベント捕捉時を書くときに役立つ。