Design Patterns – Data Binding in Event-Driven Architecture

Architecturedesignevent-programmingwebsockets

I develop a browser based game with node.js in back and HTML5 canvas in front-end.
It use WebSockets for communication.

My plan is to generate business events in client side, e.g.: "finishJob".
Client will store all relevant information up to date.

  • client doesn't have to call server every time it need some data e.g: players money
  • to achieve this, client will subscribe to players channel
  • every online player has its own channel, like a chat room
  • every time something happen with a player, its channel fire an event with players new data

In MVC pattern in here the model is Player, the View is the HTML5 Canvas, but i need 2 type of controllers:

  1. controller to handle business events
  2. controller to handle channels and subscribers

My questions: Is this a viable option?
If yes, are there any design pattern similar for this, or any article about this kind of architecture? Are there any naming conventions ("controllers", "handlers", "channels"…)?

Best Answer

Yes

...see the link below for this pattern...

If you're writing an application which uses Peers -- or any complex app which requires robust Object-Networks I would use an Event-Driven Architecture.

Using a Mediator or EventHub (Event-Aggrigator)

The simplest approach would be to implement the Mediator Pattern designed by Addy Osmoni.

This allows you to write something like:

// core.js
mediator.subscribe('newMemberAdded', function newMemberAddedHandler(id){
    this.membersModule.add(id);
});

...

// membersUI.js
$('#addMember').click(function(){
    ...
    mediator.publish('newMemberAdded', 998);
    ...
});

With this, the only Coupling your modules require is a reference to mediator in order to communicate with other modules.

Using a Mediator is very powerful and will make your modules more Liftable (loose coupling), however, there are some conventions you should consider while developing an EDA:

  • Modules only publish interests -- not Query+Command events
    • e.g: eventHub.fire('buttonClicked') NOT eventHub.fire('get:membersList', function(){ ... })
  • Query+Command Channels Are reserved for Core/Facade interaction (see Osmoni's post)
  • Work-around those Noun-Verb-Adjective channel-names:
    • e.g: 'log', 'start', 'change', 'notice' all can be seen as a command or something that happend. You can add the ing conjugate to obviate this ('starting')
  • Listen Before You Speak! -- Otherwise you may miss events
  • Visit the link above for more

Additionally, you can bind your Mediator to a WebWorker or SharedWorker to share state between browser tabs (etc) and bind your worker to an EventHub on your server for an even cleaner coupling.

I know this post is somewhat ad hoc, but I hope its enough to get you started!