Skip to main content
4 of 6
added 293 characters in body

looks good to me, but your questions are hard to evaluate with such a small snippet.

(1) Efficiency

Basically, what else can you do? You have to iterate over all registered events.

(2) Organisation

Seems like a good idea to me. This way you would have central point for binding events to DOM elements - if i'm understanding your code correctly.

(3) OOP

Go for it!

(4) Context

This is problematic, but not dramatic! Basically your .off function does not keep the to arrays in sync. - which is really hard, because events are asynchronous. Consider this example with simple inheritance:

<html>
<body>
<div id="clickMe">Click Me!</div>
<script>
(function(){

    var Hub = Object.create ({});
    //initialize this hub
    Hub.init = function () {
     this.events = {};
     this.contexts = {};
     return this;
    };
    //register a function and context
    Hub.on = function (name, callback, contexts) {
     // create event type if it isn't already and push our callback
     (this.events [name] || (this.events [name] = [])).push (callback);
     (this.contexts [name] || (this.contexts [name] = [])).push (contexts);

     
    };
    //un-register a function
    Hub.off = function (name, callback) {
     // if this event type exists, splice out our callback
     console.log(this.events [name].indexOf (callback));
     console.log((this.events));
     console.log(JSON.stringify(this.contexts));
     this.events [name] && this.events [name].splice (this.events [name].indexOf (callback), 1);
     this.contexts [name] && this.contexts [name].splice (this.events [name].indexOf (callback), 1);
     console.log((this.events));
     console.log(JSON.stringify(this.contexts));
    };
    //fire all of a type of functions
    Hub.trigger = function (name) {
          
     if (!this.events [name] || this.events [name].length === 0) return;
     var args = Array.prototype.slice.call (arguments, 1),
         i = 0, event = this.events [name], context = this.contexts [name], l = event.length;
     // if this event type exists, run all the callbacks
     for (; i < l; event [i].apply (context [i++], args));


    };


    var Main = {};

    Main.hub = Object.create(Hub);
    Main.hub.init();


    var Foo = {};
    Foo.init = function (name) {

        this.name = name;
        Main.hub.on("lala", this.onClick, this);
    
    };
    Foo.onClick = function Foo_onClick (){

        alert(this.name);
    
    };

    var Bar = Object.create(Foo);;
    Bar.init = function (name) {

        Foo.init.call(this, name);
    
    
    };
    Bar.onClick = function Bar_onClick (){

        Foo.onClick.call(this);
        Main.hub.off("lala", this.onClick);

    };

    var f = Object.create(Foo);
    var b = Object.create(Bar);
    var c = Object.create(Foo);

    f.init("foo");
    b.init("bar");
    c.init("c");

    console.log(Object.is(f,c));

    var clickMe = document.getElementById("clickMe");
    clickMe.addEventListener("click",function(e){

        Main.hub.trigger("lala",e);
    
    });


}());
</script>
</body>
</html>

Here, calling Hub.off inside an event callback forces Hub.events.length to decrement while i in Hub.trigger is still incementing, so event[i] will be undefined. Also this.events[name].indexOf(callback) will give a different result in the second line:

this.events [name] && this.events [name].splice (this.events [name].indexOf (callback), 1);
this.contexts [name] && this.contexts [name].splice (this.events [name].indexOf (callback), 1);

(5) Messes

Besides (4) i'd recommend another formating style, yours is really hard to read. This is important, if you consider your product to be maintained in the long run.

(6) Solution for asynchronous calls for .on and .off

Here is a solution for a Hub, which can deal with asynchrounous calls of .on and .off. I also made some minor API changes, which strictly (un-)registers only pairs of (callback, context). I'm not certain if this is necessary for unregister, but it markes the API more symmetric.

var Hub = Object.create ({});
// initializes Hub
Hub.init = function () {

    this._handlers = {};     // centra registry for custom events
    this._running = false;   // determines if custom evetns ar triggered

};

// delays the exectuion of fn while Hub is triggering custom events (_running === true)
Hub._delay = function Hub_delay (fn) {

    var hub, interval, id;

    hub = this;
    interval = 0;

    // setInterval(fn,0) is the JS equivalent for while(true){}
    // the actual while(true) will certainly kill the process
    id = setInterval(function(){

        if (!this._running) {

            fn.call(hub);
            clearInterval(id);
            
        }
        
    },interval);
    
};

// registers the pair (callback, context) for the custom event name
Hub.on = function Hub_on (name, callback, context) {

    this._delay(function Hub_on_delayed (){

        var handler;
        
        if (!Array.isArray(this._handlers[name])) {

            this._handlers[name] = [];
            
        }

        handler = {};
        handler.callback = callback;
        handler.context  = context;

        this._handlers[name].push(handler);
                    
    });
    
};

// unregisters the pair (callback, context) for the custom event name
Hub.off = function Hub_off (name, callback, context) {

    this._delay(function Hub_off_delayed (){

        if (!Array.isArray(this._handlers[name])) {

            this._handlers[name] = [];
            
        }
        
        console.log(JSON.stringify(this._handlers[name]));
        
        this._handlers[name] = this._handlers[name].filter(function(handler){

            return !(handler.callback === callback && handler.context === context);
            
        });

        console.log(JSON.stringify(this._handlers[name]));
        
    });
    
};

// triggers all handlers for the custom event name
Hub.trigger = function Hub_trigger (name) {

    var args, i, handlers, callback, context, invoke;

    // delay asynchronous registering and unregistering
    this._running = true;

    args = Array.prototype.slice.call (arguments, 1);
    handlers = Array.isArray(this._handlers[name]) ? this._handlers[name] : [];

    for (i = 0; i < handlers.length; i++) {

        callback = handlers[i].callback;
        context  = handlers[i].context; 
        
        // allow invokation only fo valid callbacks and contexts
        invoke = (
            typeof callback === "function" 
            && typeof context !== "undefined"
            && context !== null
        );
        
        if (invoke === true) {

             callback.apply(context, args);
            
        }
        
    }
    
    // allow registering and unregistering
    this._running = false;
    
};