11550 sujets

JavaScript, DOM et API Web HTML5

// by dessy boris
// for test just include jQuery in a html page and this file(name it : "handler.js")
// sample like this :
/*
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="handler.js"></script>
*/
// welcome ^^

var handler = {
		log : function(msg,type){
				var p = type=='function'?'()':'';	
				console.log(type+' : '+handler.level+msg+p);
				// logFile isn't used here, but you can use for send packet with all log to your server via ajax.
				handler.logFile.push(type+':'+msg);
		},
		exception : function(err,o,arg,name,f){
				handler.log(err,'## error');
				// -- you can do lot of things to handle your error here
				//-----------------
				// fn.name = name;
				// fn = f;
				// fn.caller =  arguments.callee.caller.caller
				// object = o;
				// arguments = arg;
				// error = err;
				//-----------------
		},
		create : function(f,name){	
				// return a new function to replace original
				return function(){
					// log function call
					handler.log(name,'function');
					// increment deep level of call
					handler.level += '--';
					// make the call and catch(+log) error
					try{ 	var r = f.apply(this,arguments);	}
					catch(e){	 handler.exception(e,this,arguments,name,f);		}
					// decrement deep level of call
					handler.level = handler.level.substr(2);
					// return value of call
					return r;
				};
		},
		init : function(o,restrict){
				handler.log('_begin','handling');
				// browse all functions of the object (except the restricted)
				for(var i in o) if(typeof o[i] == 'function') if(!restrict || restrict[i]==undefined){
					// overwrite each function with new
					o[i] = handler.create(o[i],i);	
				}
				handler.log('_end','handling');	
		},
		logFile : [],
		level : ''
};

myOwnFn = {};

		
$(document).ready(function() {
	// create console if none is define		   
	if(!window.console){
		window.console = document.createElement('div');
		console.setAttribute('style','position:absolute;top:0;right:0;height:150px;width:400px;border:solid black 1px;overflow:auto;background-color:white;');
		console.innerHTML = '<b>CONSOLE:</b><br/>';
		document.body.appendChild(console);
		console.log = function(msg){this.innerHTML += '-'+msg+'<br/>';this.scrollTop=999999;};
	}
	console.log('console : initialized');
	
	
	// SAMPLES :
	
	// handling myOwnFn
	handler.init(myOwnFn);
	
	// handling jQuery.fn
	handler.init(jQuery.fn,{init:1});
	
	// sample of use (of jQuery)
	$('<div id="test">hello world(click me)</div>').appendTo('body');
	$('#test').click(	function(){	$('#test').fadeOut();}		);
});


Voila, je viens de coder ça en une petite heure (donc, oui, il y a encore certainement plein d'erreurs.)

Mais je voudrais connaitre votre avis sur ce bout de code ? Intéressant ? Inutile ? Toutes critiques seront les bienvenues. Smiley cligne

Pour le tester, ajoutez simplement jQuery et ce bout de code à une page vierge. (sous Chrome, j'utilise la console du navigateur, pour les autres je créé un div qui affiche les logs.)

Evidement, dans certains cas, certaines fonctions ne pourront pas être remplacées pour diverses raisons. (appel au "caller" ou utilisation de variables locales ou que sais-je?). Pour ce faire, j'ai prévu un paramètre qui permet de spécifier les fonctions qu'on ne souhaite pas remplacer. Comme par exemple la fonction "init" de jQuery.fn qui faisait planter le bazar. (mais justement grâce à ce gestionnaire d'erreurs, j'ai pu voir directement la fonction qui posait problème ! l'est pas belle la vie ? )

Smiley lol [/i][/i][/i][/i]
Modifié par bogs (08 Feb 2011 - 20:47)
première correction :
la surcharge de la fonction "init()" de jQuery ne fonctionnait pas car elle était appelée par un "new". j'ai donc rajouté la gestion des fonction "constructeurs" qui instancient de nouveaux objets :

CORRECTION:
if(this instanceof arguments.callee){ // = explicit new object
							function f_() {
    							return f.apply(this, arguments);
							}
							f_.prototype = f.prototype;
							var r = new f_();
						}
						else
							var r = f.apply(this,arguments);


CODE COMPLET:
// by dessy boris
// for test just include jQuery in a html page and this file(name it : "handler.js")
// sample like this :
/*
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="handler.js"></script>
*/
// welcome ^^

var handler = {
		log : function(msg,type){
				var p = type=='function'?'()':'';	
				console.log(type+' : '+handler.level+msg+p);
				// logFile isn't used here, but you can use for send packet with all log to your server via ajax.
				handler.logFile.push(type+':'+msg);
		},
		exception : function(err,o,arg,name,f){
				handler.log(err,'## error');
				// -- you can do lot of things to handle your error here
				//-----------------
				// fn.name = name;
				// fn = f;
				// fn.caller =  arguments.callee.caller.caller
				// object = o;
				// arguments = arg;
				// error = err;
				//-----------------
		},
		create : function(f,name){	
				// return a new function to replace original
				return function(){
					// log function call
					handler.log(name,'function');
					// increment deep level of call
					handler.level += '--';
					// make the call and catch(+log) error
					try{ 	
						if(this instanceof arguments.callee){ // = explicit new object
							function f_() {
    							return f.apply(this, arguments);
							}
							f_.prototype = f.prototype;
							var r = new f_();
						}
						else
							var r = f.apply(this,arguments);	
					}
					catch(e){	 handler.exception(e,this,arguments,name,f);		}
					// decrement deep level of call
					handler.level = handler.level.substr(2);
					// return value of call
					return r;
				};
		},
		init : function(o,restrict){
				handler.log('_begin','handling');
				// browse all functions of the object (except the restricted)
				for(var i in o) if(typeof o[i] == 'function') if(!restrict || restrict[i]==undefined){
					// overwrite each function with new
					o[i] = handler.create(o[i],i);	
				}
				handler.log('_end','handling');	
		},
		logFile : [],
		level : ''
};

myOwnFn = {};

$(document).ready(function() {
	// create console if none is define		   
	if(!window.console){
		window.console = document.createElement('div');
		console.setAttribute('style','position:absolute;top:0;right:0;height:150px;width:400px;border:solid black 1px;overflow:auto;background-color:white;');
		console.innerHTML = '<b>CONSOLE:</b><br/>';
		document.body.appendChild(console);
		console.log = function(msg){this.innerHTML += '-'+msg+'<br/>';this.scrollTop=999999;};
	}
	console.log('console : initialized');
	
	
	// SAMPLES :
	
	// handling myOwnFn
	handler.init(myOwnFn);
	
	// handling jQuery.fn
	handler.init(jQuery.fn);
	
	// sample of use (of jQuery)
	$('<div id="test">hello world(click me)</div>').appendTo('body');
	$('#test').click(	function(){	$('#test').fadeOut();}		);
});



ps: jQuery n'est qu'un exemple de surcharge ici, mon code n'utilise pas jQuery. Smiley smile [/i][/i][/i][/i]
Modifié par bogs (09 Feb 2011 - 17:09)