1
votes

I have two custom Sprites (in my case on is Sprite, another is Container, but this doesn't matter). I need to emit event in one sprite and listen to it in another sprite (MyDragableElement). In Application I have many MyDraableElements: PIXI.Sprite. The idea is that second sprite will be able to manipulate on MyDragableElement, but it should know which element is selected. I decided that events can help here, but how this should be written in Typescript?

export class MyDragableElement extends PIXI.Sprite {
    constructor(

     super();

        this
        .on('pointerdown', this.onDragStart)
        .on('pointerup', this.onDragEnd)
        .on('pointerupoutside', this.onDragEnd)
        .on('pointermove', this.onDragMove);
    }

    private onDragStart(event) {
        this.emit('selectedElementChanged', this);
    }
}

So as you see this is some sprite and on drag start, it should emit global event.

Here is another Sprite, and it should listen to this event.

export class Toolbar extends PIXI.Container {
    selectedGameObject: any;

    constructor()
    {
        super();
        this.addListener("selectedElementChanged", 
                (e:any) =>  { 
                    // this.selectedGameObject = need to select this element
                    console.log(e); 
                });
        }
     }
  }

Above is my idea, but it worn't work. No experience in Emitting events.

1

1 Answers

1
votes

I just learned this topic and can be wrong, but...

if you have some sprite

let mySprite = new Sprite(someTexture);

... you can write somewhere in you code the next:

mySprite.emit('customEvent', {myData: 'somedata'});

And you also need to set event handler for this customEvent on your sprite:

mySprite.on('customEvent', onCustomEvent);

let onCustomEvent = (event) => {
    console.log(event);
};