See this reply with links to other topics …
Recreate Move Tool - #8 by DanRathbun
place_component() is a quirky method.
It creates an undo operation so you cannot put a call to it inside another undo operation.
It also is asynchronous. It means that the Ruby code does not stop and wait for the component instance to be placed into the model.
So hopefully reading those old topics will help you know the way to code.
Please learn to search categories using the magnifying glass menu at top right.
You will not use the onPlaceComponent observer callback. Instead you know what the definition is, so you will instead use the DefinitionObserver#onComponentInstanceAdded callback.
As an example, you create a little hybrid observer:
class PlaceInstanceSpy
def initialize(definition, parent)
@definition = definition
@parent = parent
# Attach this observer also to watch the tools collection
# because the active tool changes as the placement proceeds:
@definition.model.tools.add_observer(self)
end
def onComponentInstanceAdded(definition, instance)
# Set attributes on the definition or the instance here,
# by calling a method in the parent module:
@parent.set_attribut(definition, instance)
# Remove this observer instance. No longer needed.
definition.remove_observer(self)
end
def onActiveToolChanged(tools, tool_name, tool_id)
if tool_id == 21013 # ComponentTool
# User has begun the component placement.
# Status bar text says "Place component."
elsif tool_id == 21048 # MoveTool
# User has clicked and placed the instance.
# Stop watching the tools collection:
tools.remove_observer(self)
# User is left with MoveTool active and new instance selected.
elsif tool_id == 21022 # SelectionTool
# User has cancelled the placement via ESC key.
# Stop watching the definition:
@definition.remove_observer(self)
# Stop watching the tools collection:
tools.remove_observer(self)
end
end
end
Later on in the code use it when placing a component:
# Attach Observer to cdef definition, (self is parent module):
cdef.add_observer(PlaceInstanceSpy.new(cdef, self))
# Start the placement:
model.place_component(cdef)