Events

Every change on the workspace triggers an event. These events fully describe the before and after state of each change.

Listening to Events

Workspaces have addChangeListener and removeChangeListener methods that can be used to listen to the event stream. One example is the real-time generation of code. Another example is the maximum block limit demo. As is often the case, neither of these two examples care what the triggering event was. They simply look at the current state of the workspace.

A more sophisticated event listener would look at the triggering event. The following example detects when the user creates their first comment, issues an alert, then stops listening so that no further alerts are triggered.

function onFirstComment(event) {
  if (event.type == Blockly.Events.BLOCK_CHANGE &&
      event.element == 'comment' &&
      !event.oldValue && event.newValue) {
    alert('Congratulations on creating your first comment!')
    workspace.removeChangeListener(onFirstComment);
  }
}
workspace.addChangeListener(onFirstComment);

In order to listen to any events that happen inside of a flyout a listener can be added to the flyout's workspace.

var flyoutWorkspace = yourWorkspace.getFlyout().getWorkspace();
flyoutWorkspace.addChangeListener(onFirstComment);

Blocks have another method of listening to the event stream. A block can define an onchange function or use setOnChange to set a function that will get called whenever a change occurs on the block's workspace.

Event types

Refer to the reference documentation for information about individual events.

Demo

For an example of the cool things you can do with events, you can check out the mirror demo. This demo has two Blockly workspaces that are kept in sync using events.