Correct way of making model changes inside ModelChangedListener

I have a modelChangedListener that will remove a dynamic port from a specific node when a link connected to it is removed.

This is the listener definition

gojsDiagram.addModelChangedListener(e => {
  if (e.change === go.ChangeType.Remove && e.propertyName === 'linkDataArray') {
    const linkData = e.oldValue;
    
    const nodeData = e.model.findNodeDataForKey(linkData.from);
    
    if (nodeData && nodeData['category'] === 'generic-group') {
      const outletPorts = nodeData['outletPorts'];
      
      const portIndex = outletPorts.findIndex(p => p.linkRef = linkData.key);
      
      if (portIndex > -1) {
        e.model.removeArrayItem(outletPorts, portIndex);
      }
    }
  }
});

My question is, should I wrap ` e.model.removeArrayItem(outletPorts, portIndex);` inside a transaction? or, does the modelChangeListener already wraps any nested changes in a transaction?

Thank you!

That code is executed when the change happens, which may or may not be within a transaction. Certainly all of the predefined such changes, such as by the CommandHandler.deleteSelection command, are performed within a transaction.

I should caution you that making changes to a model within a model changed listener might cause problems, depending on the side-effects.

Hello Walter, thanks for the quick reply.

I see, so making model changes inside the change listener is not the best approach. Previously we were using the SelectionDeleting event for this task, however it failed to detect when a link was cascade-deleted when deleting one of the attached nodes.

I’d be thankful if you could point me in the right direction.

Basically, what I need to accomplish is to correctly update a model property of a node when an attached link is removed from the diagram.

Implement a Node.linkDisconnected event handler. Node | GoJS API

Will do.
Thank you!