EVC - JS Core

JS Core with only a little jQuery used

by AaronLayton

HTML

<button id="btnTest" onclick="">Test Button</button>

JavaScript

// Javascript Mediator Pattern
// List-based Publish-Subscribe design pattern


window.numClick = 0;
// Create our new core 
// @param {object} Reference to the window
// @param {object} Reference to the jQuery (works even in $.noConflict mode)
// @param {undefined} Nothing passed so we can a true undefined reference
var Core = (function(window, $, undefined){
    
    // Internal logging function
    var log = function(){
        log.history = log.history || [];   // store logs to an array for reference
        log.history.push(arguments);
        if(window.console) {
            arguments.callee = arguments.callee.caller;
            var newarr = [].slice.call(arguments);
            (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
        }
    },
    
    // Used to add hooks
    AddAction = function(hook, fn){
        // If the hook doesn't exist then blank array
        if (!Core.allHooks[hook]) Core.allHooks[hook] = [];
        
        // Push a reference to the passed function for this hook
        // Also store the context incase added to another element
        Core.allHooks[hook].push({ context: this, callback: fn});
        return this;   
    },
    
    DoAction = function(hook){
        // If the hook doesn't exist then return false
        if (!Core.allHooks[hook]) return false;
        // Get all passed arguments
        var args = [].slice.call(arguments, 1);
        
        for (var i = 0, l = Core.allHooks[hook].length; i < l; i++){
            var action = Core.allHooks[hook][i];
            action.callback.apply(action.context, args);
        }
        return this;
    };
    
    // return public facade
    return {
        allHooks: {},
        log: log,
        AddAction: AddAction,
        DoAction: DoAction 
    }
}(window, jQuery));

// Test Core logging
Core.log("Log this message");

// We add actions anywhere we want
Core.DoAction("core-loaded");

// Add an...