0
\$\begingroup\$

Just as I was told here, I need to make some kind of communication between objects in my game. Mainly, for achievements. How do I do this? My idea was to make every object have an array attached to itself called "messages", and then, when something happens, a message gets pushed there. At the end, I would have a big loop, where I would check messages that each object got, remove them, and act accordingly. I could also have a global array called "messages", and then I would iterate through it, and fire off events in different objects that the messages were sent to (in this case, a message would contain both a message, and some kind of an object ID), and then remove them. Is there a better way? Keep in mind that I'm working in Javascript.

I forgot to mention, we're talking about serverside Javascript running on Node.js, not in a browser.

\$\endgroup\$

3 Answers 3

2
\$\begingroup\$

Why don't you just register events?

Different objects act upon events they listen to, and you can attach some datas to these events (an object like {key: 'value', key2: 'value2'}, for example).

If basic events (click, change, etc) don't satisfy you, you can register custom events. An example of how to do this here : http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

Edit : heh, even easier in Node.js ! There is an event module available. Look at this link : http://venodesigns.net/2011/04/16/emitting-custom-events-in-node-js/

\$\endgroup\$
0
\$\begingroup\$

JavaScript already uses events internally, so you could leverage that system for your game messages. While there's apparently a W3C specification for custom events, it isn't really supported in all browsers.

Here's an article that explains a possible implementation of custom events. On the other hand you could simply use a framework like YUI, which has custom events implemented and ready to use.

\$\endgroup\$
1
  • \$\begingroup\$ I forgot to mention thta I'm working on Node.js, not in a browser... \$\endgroup\$
    – jcora
    Commented Feb 17, 2012 at 10:11
0
\$\begingroup\$

This calls for the Observer Pattern! Seems like Node.js already has something like it, called an EventEmitter. A similar question was asked in the Programmers StackExchange.

Hopefully this will start you on the right track!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .