Event when child added to object/group

Is there any dispatch event I can listen for when an object is added as a child object?

I’ve created an automatic vertical and horizontal layout system. I’m periodically traversing the scene graph to look for any new meshes that I can attach a listener to. Child objects can notify this listener when their height or wide changes.

I could avoid this periodic traversal if there was a way to be notified when a child was added.

Objects dispatch ‘added’ event when they are added to the parent, so this will work, not sure how much it helps in your case:

const scene = new THREE.Scene();
const lightA = new THREE.AmbientLight(0xff0000, 0.2);

lightA.addEventListener('added', event => { console.log('triggered:', event) });

scene.add(lightA);

there is also ‘removed’ event.

Thanks, I knew about this. I’m looking for the parent to be notified, not the object being added.

Looks like it isn’t possible without modifying the threejs code based.

Is anyone else interested in having this feature added?

Why do you need to notify the parent? When you .add() something to it, you know when it happens and what is being added.

In any case Object3D has .parent property, so

lightA.addEventListener('added', event => { /* notify lightA.parent */ });

he wants to dynamically react to add/remove in a sub tree, for instance to trigger reflow if the end user adds something. added on the child isn’t enough, unless you make the api imperative where you have to inform the service, similar to needsUpdate in threejs.

i think having a childAdded/Removed event would be useful, open an issue @anidivr

btw, having fought with this myself, even if added to three this won’t be a solution since add/remove is only half the rent. the user can change scale, position, etc, which will derail it. we have made a layout system as well and while we do detect all the obvious changes, we exposed reflow() so the user can call it in situations where it wouldn’t be able to, check out Invalidation and Reflow: GitHub - pmndrs/react-three-flex: 💪📦 Flexbox for react-three-fiber

You nailed it. I use dispatch event to keep it independent of any framework. It’s a very powerful messaging system that I don’t think most understand.

I’ll open an issue and see if anyone takes it.