LoginSignup
0
0

【JointJS】JointJSのイベント処理

Posted at

JointJSで描画しているSVGにはイベントを設定することができます。今回はどんなイベントが設定できるのかを紹介していきます。

設定単位

JointJSでは、以下の単位でイベント処理を定義できます。

  • Graph
  • Paper
  • Element
  • Link

それぞれの設定単位について、どのような設定ができるのかを紹介します。

Graphに設定できるイベント

GraphではGraphに対しての変更が生じるタイミングをトリガーとしたイベントを設定できます。また、Graph内に存在しているすべてのElement, LinkのイベントはGraphに対しても伝搬されます。

使用できるイベント

  • change:Graph内のすべての変更イベントに対して発火する
  • add:GraphにCellが追加されたタイミングで発火する
  • remove:GraphからCellが削除されたタイミングで発火する
graph.on('change', function() {
  console.log('何かしらの変更が発生しました')
});

let cellCounter = 0;

graph.on('add', function() {
  cellCounter++;
});

graph.on('remove', function() {
  cellCounter++;
});

Paperに設定できるイベント

Paperの各種イベントに対して処理を設定することができます。Paperのイベントについては過去の記事で既に触れておりますので、この記事ではこれ以上は触れません。

Elementに設定できるイベント

Elementには、Elementの変更に対するイベントが設定できます。また、Elementからイベントを発行することもできます。

Elementの変更に対するイベントは、change:positionなどのイベントをon()メソッドに設定します。

Elementのevent属性に文字列を設定すると、その文字列のカスタムイベントを発行できます。カスタムイベントはPaperやGraphで捕捉できます。
eventという名前ですがクリックイベント(正確にはmousedown/touchstartイベント)のみしか扱えないことに注意してください。クリックイベント以外のイベントを扱わせるためには別のアプローチが必要になります。

コード例

var paper = new joint.dia.Paper({
  el: document.getElementById('myholder'),
  model: graph,
  width: 600,
  height: 100,
  drawGrid: "mesh",
  gridSize: 10,
  cellViewNamespace: namespace
});

// 黄色い四角形(移動で変化)
const rectangle1 = new joint.shapes.standard.Rectangle({
  size: { width: 150, height: 40 },
  position: { x: 10, y: 30 },
});
rectangle1.attr('label/text', `テキスト初期値`)
rectangle1.attr('body/fill', 'yellow');
rectangle1.on('change:position', function(ele, position) {
  rectangle1.attr('label/text', `x: ${position.x} y: ${position.y}`)
})

// 青い四角形(クリックで変化)
const rectangle2 = new joint.shapes.standard.Rectangle({
  size: { width: 150, height: 40 },
  position: { x: 10, y: 130 },
  attrs: {
    body: {
      event: 'rect2.click'  
    }
  }
});
rectangle2.attr('label/text', 'テキスト初期値');
rectangle2.attr('body/fill', 'lightblue');

paper.on('rect2.click', function(elementView, evt) {
  elementView.model.attr('label/text', 'クリックされた');
});

実行結果

dadlink.gif

Linkに設定できるイベント

Linkのイベントも、Elementと同様にLinkの変更に対するイベントの設定と、Linkからのイベント発行ができます。

前者のLink変更に対するイベントについては、Linkの場合change:source(起点),change:target(終点),change:vertices(経由点)などのLinkのルート変更に関するイベントが設定できるようになっています。

まとめ

JointJSでは様々なイベントの設定単位が利用できます。ユーザーの操作に対すて適切なイベントを設定できるように、イベントの種類と動作を把握しておくことが重要です。

※この記事は JointJS Advent Calendar 2023 の記事です。他の記事を読む場合はカレンダーのページを参照してください。

0
0
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
0
0