Skip to main content

Events

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

Listen to events from the workspace​

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

Listen to events from blocks​

Blocks can have change listener functions that are called on any change to the workspace (including those unrelated to the block). These are often used to set the block's warning text, or similar user notification outside the workspace.

The function is added by calling Block.setOnChange with a function and can be done during initialization or via a JSON extension if you plan to use it on all platforms.

{
// ...,
"extensions":["warning_on_change"],
}

Blockly.Extensions.register('warning_on_change', function() {
// Example validation upon block change:
this.setOnChange(function(changeEvent) {
if (this.getInput('NUM').connection.targetBlock()) {
this.setWarningText(null);
} else {
this.setWarningText('Must have an input block.');
}
});
});

You can also set the onchange property directly on the block:

Blockly.Blocks['block_type'] = {
init: function() {
// Example validation upon block change:
this.onchange = function(changeEvent) {
if (this.getInput('NUM').connection.targetBlock()) {
this.setWarningText(null);
} else {
this.setWarningText('Must have an input block.');
}
};
}
}

The system calls the function, passing in the change event. Inside the function, this refers to the block instance.

Because the function is called on any change, if used, developers should ensure the listener runs quickly. One should also be wary of changes to the workspace that might cascade or loop back to the listener.

See the controls_flow_statements, logic_compare, and procedures_ifreturn blocks for examples.

Note that editable fields have their own event listeners for input validation and causing side effects.

Setting an event group​

You may need to to group related events so that your user's actions can be properly undone.

For example, consider the "Clean up Blocks" item on the context menu. It takes one action from the user to clean up the blocks. However, the process of cleaning up the blocks involves moving every block on the workspace into a column. In practice, Blockly groups these events so that an undo action will undo all of these move events at once, rather than one at a time.

Before calling setGroup to set an event group, you should always fetch the current group with getGroup. This ensures that you do not set up a new event group while another group already exists.

const existingGroup = Blockly.Events.getGroup();
if(!existingGroup){
Blockly.Events.setGroup(true);
}

// The code that you'd like to group

Blockly.Events.setGroup(existingGroup);

Events in a group will all still fire, but they will be grouped in the undo stack.

Disabling undo/redo​

Event groups are a helpful tool for grouping related events, but sometimes your app may have operations that should not be part of the undo stack at all. This can be the case when there are programmatic changes that you don't want your users to be able to undo. For example, core Blockly disables adding events to the undo stack when populating the flyout with blocks, so that users can't undo blocks from existing in the flyout.

Similar to setting an event group, it's best practice to check first whether undo is already disabled with getRecordUndo before calling setRecordUndo. That way, you don't prematurely re-enable the undo stack while another process has disabled it.

const undoEnabledPreviously = Blockly.Events.getRecordUndo();
Blockly.Events.setRecordUndo(false);

// Actions that you don't want on the undo stack

if(undoEnabledPreviously){
Blockly.Events.setRecordUndo(true);
}

Disabling events​

Disabling events should be done with caution, since core Blockly and many plugins rely on events to update various parts of the workspace. Before disabling events, consider whether you can accomplish your goal by disabling undo/redo or grouping events.

Disable events with disable. All calls to disable must also call enable afterward to re-enable events.

Event types​

Refer to the reference documentation for information about individual events.

Events are registrable and can be swapped out, so if you intend to fire an event, it's best to fetch that event from the registry rather than hard-coding the event type. For example, do:

const newEvent = new (Blockly.Events.get(Blockly.Events.BLOCK_CHANGE))(
// parameters for BLOCK_CHANGE event go here
);

instead of:

const newEvent = new Blockly.Events.BlockChange(
// parameters for BLOCK_CHANGE event go here
)

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.