Skip to content

Signal Event System

Mark Knol edited this page Jan 17, 2018 · 24 revisions

Flambe does not know the concept of events but uses an own implementation of signals.

Listening to signals

You can listen to a signal using the connect-function.
Listen to stage resize signal

// System.stage.resize is a Signal, listen to it.
System.stage.resize.connect(onResize);

private function onResize()
{
   trace('stage has just resized!');
}

Create own signal

// create signal (which dispatches one string).
public var messageSignal:Signal1<String> = new Signal1<String>(); 

// add listener
messageSignal.connect(onMessage);
private function onMessage(value:String)
{
   trace(value); 
}

// dispatch
signal.emit("hello"); 

One-shot connections

Tells the connection to dispose itself after being used once.

signal.connect(function() {...}).once();

💥 Dispose signals

You can 'connect' signals yourself, but these are not automatically disposed from your current context. If you want to remove signals manually, the connect function returns a SignalConnection, which is disposable. Another option is to add a Disposer component to your Entity, and connect the signals via the Disposer. When the Disposer is disposed, the signal-connections are released (removed).

Using a Disposer instance

_disposer.add(System.stage.resize.connect(onResize)); // wrap function in _disposer.add

private function onResize():Void
{
	trace("Resize");
}

.. Since Disposer is a Component, you can choose to add it to your Entity, otherwise you have to call _disposer.dispose() to remove registered connections manually. I found both can be handy in different cases.

Full example; Create auto removing listeners / signal connections

Some notes on following example; No need to remove the Disposer instance anywhere, since all components are disposed when an entity is disposed. The Disposer automatically removes connections, so no need to remove signal connections anywhere manually.

private var _disposer:Disposer;
	
override public function onAdded():Void 
{
	super.onAdded();
	
	_disposer = owner.get(Disposer); // grab disposer out of entity
	if (disposer == null) owner.add(_disposer = new Disposer()); // .. or add one when there is none 
	
	// add signal connections to the Disposer
	_disposer.add(mySprite.pointerDown.connect(onPointerDown)); 
	_disposer.add(mySprite.pointerUp.connect(onPointerUp));
}

private function onPointerDown(event:PointerEvent):Void { 
	trace('pointer down');
}
private function onPointerUp(event:PointerEvent):Void { 
	trace('pointer  up');
}
Clone this wiki locally