Game engine API · Lesson 5
Event Listeners
Subscribe with olay(ad, fn), use the wildcard * listener, and cancel with the returned function. See why one failing listener cannot stop the engine.
The engine publishes events; your code reacts to them. Subscriptions are idempotent and every one of them can be cancelled.
What you will learn
- The olay(ad, fn) signature and cancel function
- The wildcard * listener
- Core and module event names
API signatures
| Call | Result |
|---|---|
olay(ad, fn) | function that cancels the subscription |
basla(mod, config) | {ok, hata?} · validates mode and config |
puanAta(deger, sebep) | {ok, hata?} · emits puan on change |
sahneYukle(ad, veri) | {ok, hata?} · needs a running session |
Subscribe and cancel
With an invalid name or function, olay() returns an empty function and does not throw. The same callback is never added twice to one event.
The returned function can be called once; a second call has no effect. This prevents listener leaks.
Set up three subscriptions
var M = window.OyunMotoru;
function puanYaz(e) {
console.log('Score:', e.puan, e.sebep);
}
var kapatPuan = M.olay('puan', puanYaz);
M.olay('puan', puanYaz); // same callback: not added again
var kapatTum = M.olay('*', function (e) {
console.log('Event name:', e.ad, e.detay);
});
M.basla('2d', { kok: document.getElementById('oyunAlani2D'), oyun: 'labirent' });
M.puanAta(10, 'deneme');
kapatPuan();
kapatTum();What happens in this code? A wildcard listener receives ad and detay in its detail object. A normal listener receives only the detail object of its own event.
Which events are published?
Core: basla, duraklat, devam, durdur, sahne, puan, hata. The 2D layer adds oyun-olay and bitti. The 3D layer adds 3d-hazir and sahne.
If one listener throws, yayinla() still runs the others; a single bad callback cannot stop the engine.
Catch error and game events
var M = window.OyunMotoru;
M.olay('hata', function (e) {
console.log('Engine error:', e.mesaj);
});
M.olay('3d-hazir', function (e) {
console.log('Scene ready:', e.oyun);
});
M.olay('oyun-olay', function (e) {
console.log('Game event:', e.ad);
});
M.basla('2d', { kok: document.getElementById('oyunAlani2D'), oyun: 'labirent' });What happens in this code? oyun-olay comes from the 2D module and carries game-specific events such as yildiz, bonus and puan.
Common mistakes
| Wrong approach | Result | Correct approach |
|---|---|---|
| Adding the same callback twice | Fear of double handling | The engine already prevents it |
| Not storing the cancel function | Listeners accumulate | Keep the return value in a variable |
| Reading wildcard details wrongly | Looking for e.puan instead of e.ad | Use e.ad and e.detay |
| Throwing inside a listener | Assuming other listeners stop | The engine continues with the rest |
Try it yourself
Subscribe two different functions to the puan event. After cancelling the first one, confirm in the console that only the second still runs.