Handsontable で 安易なテストツールを作る。

Handsontable で、任意にキーと値(value)を入力して、それをJSONテキストにするのと、任意の入力URLに送信するもの。

用意するもの。

Handsontable は、コミュニティ版で充分、https://handsontable.com/

JSONjQueryプラグイン
GitHub - Krinkle/jquery-json: [Discontinued] Use native JSON.stringify and JSON.parse instead, or json2.js from https://github.com/douglascrockford/JSON-js

handsontable のCSSと上を読むようにしたHTML

<div id="example"><!-- ここに表が展開される。 --></div>

<!-- JSON文字列生成するボタンと生成した文字列表示 -->
<div style="margin-top: 40px">
<button id="to_json" type="button">to JSON</button>
<textarea id="json_text" rows="4" cols="80"></textarea>
</div>

<!-- 送信するボタンと受信した結果をJSONにして表示するもの -->
<div style="margin-top: 40px">
<input id="target_url" type="text" placeholder="http://" style="width: 1000px">
<button id="send" type="button">to JSON</button>
<textarea id="res_text" rows="4" cols="80"></textarea>

このHTMLを前提とした jQuery ソース

var handson = new Handsontable(document.getElementById("example"), {
   data: [[null, null],],
   minSpareRows: 1,
   colHeaders: ['Key', 'Value'],
   contextMenu: { items:{
         'row_above': { name: '1行挿入' },
         'remove_row': { name: '行削除'  },
         "hsep3": "---------",
         'undo': { name: '戻る' },
      }
   },
});
$('#to_json').click(function(){
   var map = {};
   $(handson.getData()).filter(function(i, e){
      if (!handson.isEmptyRow(i)) return e;
   }).each(function(i, e){
      map[e[0]] = e[1];
   });

   $('#json_text').html($.toJSON(map));

});

$('#send').click(function(){
   var map = {};
   $(handson.getData()).filter(function(i, e){
      if (e[0] != null) return e;
   }).each(function(i, e){
      map[e[0]] = e[1];
   });

   $.ajax({
      type: 'POST',
      timeout: 10000,
      url: $('#target_url').val(),
      data: map,
      dataType: 'json',
      cache: false,
   }).done(function(e){
      $('#res_text').html($.toJSON(e));
   }).fail(function(e){
      $('#res_text').html($.toJSON(e));
   }).always(function(e){
   });
});

Handsontable の生成として、セレクタ参照に .handsontable() を付けて

$('#example').handsontable({ ...

ではなく、document.getElementById から、new Handsontable で生成することにして、

var handson = new Handsontable(document.getElementById("example"), {
   :
handson.getData()

で抽出するようにしている。

Handsontableの生成として、tutorial に書いてある Load and save では、

var
    $$ = function(id) {
      return document.getElementById(id);
    },
    container = $$('example1'),
    exampleConsole = $$('example1console'),
    autosave = $$('autosave'),
    load = $$('load'),
    save = $$('save'),
    autosaveNotification,
    hot;

  hot = new Handsontable(container, {
   :
  (省略)

と書かれており、手数が多くて嫌だ。