Javascript Method interceptors

Javascript Method interceptors

by Pradeep Kodical

HTML

<button id="btnActivate">
Activate Interceptor
</button>
<button id="btnDeactivate">
De-Activate Interceptor
</button>
<button id="btnExecute">
Execute
</button>
<div id="console">

</div>

JavaScript

Logger = {
	log : function(message){
  	$('#console').append('<div>' + message + '</div>');
  }
}

MIFactory = {
        interceptors: [],
        register: function(interceptor) {
            MIFactory.interceptors.push(interceptor);
        },
        unregister: function(interceptor) {
            var index = MIFactory.interceptors.indexOf(interceptor);
            if (index > -1) {
                MIFactory.interceptors.splice(index, 1);
            }
        },
        beforeExecution: function(o, p) {
            if (!o.__interceptors__) o.__interceptors__ = [];
            if (!o.__interceptors__[p]) o.__interceptors__[p] = [];
            for (var i = 0; i < MIFactory.interceptors.length; i++) {
                try {
                    o.__interceptors__[p].push(new MIFactory.interceptors[i]());
                } catch (e) {}
            }
    
            for (var i = 0; i < o.__interceptors__[p].length; i++) {
                try {
                    o.__interceptors__[p][i].beforeExecution(o, p);
                } catch (e) {}
            }
        },
        afterExecution: function(o, p) {
            for (var i = 0; i < o.__interceptors__[p].length; i++) {
                try {
                    o.__interceptors__[p][i].afterExecution(o, p);
                } catch (e) {}
            }
        },
        intercept: function(o) {
            for (let p in o) {
                if (typeof o[p] === 'function') {
                    let c = o[p];
                    o[p] = function() {
                        MIFactory.beforeExecution(o, p);
                        let r = c.call(o, arguments);
                        MIFactory.afterExecution(o, p);
                        return r;
                    }
                }
            }
            return o;
        }
    }

MyInterceptor = function(){
	var time;
	this.beforeExecution = function(o, p){  	
  	time = (new Date()).getTime();        
  	Logger.log('before..' + p);
  }
 ...