I came to JS from c#, so I am using class syntax/architecture.
My "handler" functions(that I want to store in Pub/Sub object), work with object's parameters(passed in the constructor) in which they are encapsulated.
But they are being stored and called as anonymous functions of undefined object.
So I came up with making PubSub's subscribe method require object, then bind Object to handler, using "handler.call(Object, args)". This allows my Object to change it's parameters in response to some event. May be it is better to use Observer pattern in this situation?
class EventBus
{
constructor() {
this.subscribers = {};
}
subscribe(subName, object, handler) {
this.subscribers[subName].push({object: object, handler: handler});
}
publish(subName, eventArgs) {
const sub = this.subscribers[subName];
sub[0].handler.call(sub[0].object, (eventArgs));
}
}
My renderer object, which functions I want to call, using events:
class Renderer
{
constructor(tileSize)
{
this.tileSize = tileSize;
}
render(tile)
{
ctx.fillText(this.getTileGraphics(tile), tile.x*tileSize, tile.y*tileSize);
}
getTileGraphics(tile){...}
}
//and this is my html code :
<script>
const eventBus = new EventBus();
var renderer = new Renderer(tileSize=32);
eventBus.subscribe("OnTileRender", renderer, renderer.render);
<script>
So is my approach fine and I can continue with this, or it's better using Pub/Sub for handlers, not dependant on outer function's parameters?
Aucun commentaire:
Enregistrer un commentaire