1

I am making a custom events object so that I can inject custom events into another object, so far I have (simplified),

function Game() {

     new Events(["pause", "resume"], this);
};

function Events(events, obj) {

     // Event object for object
    obj.events = {};

    // For each event
    events.forEach(function(event) {

        // Attach event array to store callbacks
        this.events[event] = [];

    }, obj);

     // Fire event
     obj.fire = function(event) {

         ////////////
     };

     // Add event
     obj.on = function(event, callback) {

         ////////////
     };
};

My question is, is this the right way to do this? Is it considered ok to call Event from Game and add to Game from Events? It for some reason seems wrong to me, and I do not know why?

Is there any way that I should be structuring this code that I am not aware of?

(I do not want to add Events to Game's prototype for the sole reason that Game has events and is not an extension of Events)

Thank you for taking the time to read my question.

1 Answer 1

2

My question is, is this the right way to do this? Is it considered ok to call Event from Game and add to Game from Events?

Yes, it's perfectly fine. This is called the decorator pattern. I don't see a reason for your feeling that it was wrong.

Is there any way that I should be structuring this code that I am not aware of?

Don't use new. Events is not a constructor. A better and more descriptive signature might be

function makeEventEmitter(obj, events) {
Sign up to request clarification or add additional context in comments.

3 Comments

So it's not the right way, but you do tell them the right way (don't need new)
@Juan: The pattern (which he felt wrong about) is OK, only he had syntactical issues. I mean, since he didn't store the result of the new call, it actually didn't really matter (other than being misleading and superflous)
Thank you for this @Bergi, I understand why I shouldn't now use new thanks for pointing that out. I didn't know where to begin trying to make some kind of system for custom events and ended up with this, so to know that it was ok apart from a few syntactical issues has pleased me! Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.