jQuery: ricreare lo stack di funzioni di WordPress

WordPress crea uno stack di funzioni che vengono eseguite in ordine di priorità. Possiamo fare la stessa cosa in jQuery usando i moduli.

Un modulo è un oggetto che avrà sempre un nome, due metodi fissi (inizializzazione e distruzione) e una priorità espressa come valore numerico. Possiamo creare un wrapper per gestire i moduli:


(function() {

	var Moduler = {
		modules: [],
		addModule: function( name, module, priority ) {
			if( typeof module === "object" && "init" in module && !this.hasModule( name ) ) {
				var m = {};
				m.name = name;
				m.module = module;
				m.priority = priority;
				this.modules.push( m );
			}
		},
		orderByPriority: function() {
			var allModules = this.modules;
			var ordered = allModules.sort(function( a, b ) {
				return ( a.priority - b.priority );
			});
			this.modules = ordered;
		},
		modulesAdded: function() {
			return ( this.modules.length > 0 );
		},
		hasModule: function( name ) {
		  if( this.modulesAdded() ) {
			for( var i = 0; i < this.modules.length; ++i ) {
				if( this.modules[i].name == name ) {
					return true;
				}	
			}
			return false;
		  }		
		},
		removeModule: function( name ) {
		   if( this.modulesAdded() ) {
			for( var i = 0; i < this.modules.length; ++i ) {
				if( this.modules[i].name == name ) {
					this.modules[i].module.destroy();
					this.modules.splice( i, 1 );
				}	
			}
		  	}	
		},
		getModule: function( name ) {
		   if( this.modulesAdded() ) {
			var m = {};
			for( var i = 0; i < this.modules.length; ++i ) {
				if( this.modules[i].name == name ) {
					m = this.modules[i].module;
					break;
				}
			}
			return m;
		  }
		},
		runModule: function( name ) {
		   if( this.modulesAdded() ) {
			for( var i = 0; i < this.modules.length; ++i ) {
				if( this.modules[i].name == name ) {
					this.modules[i].module.init();
				}	
			}
		   }		
		},
		bootstrap: function() {
		   if( this.modulesAdded() ) {
		   	this.orderByPriority();
			for( var i = 0; i < this.modules.length; ++i ) {
				this.modules[i].module.init();
			}
		   }
		}
	};

	window.Moduler = Moduler;

})();

Esempio d'uso:


(function( $ ) {
	
	// Creo un modulo

	var ModuleA = function( msg ) {
		this.message = msg;
	};

	ModuleA.prototype = {
		init: function() { // Inizializzazione
			this.showMsg();
		},
		destroy: function() {  // Distruzione
			$( "div" ).text( "" );
		},
		showMsg: function() {
			var self = this;
			$( "div" ).text( self.message );
		}
	};

	var a = new ModuleA( "Hello world" );
	
	// Aggiungo il modulo

	Moduler.addModule( "A", a, 1 );

	$(function() {
		Moduler.bootstrap(); // Inizializzazione di tutti i moduli
		
		$( "#destroy" ).click(function() {
			Moduler.removeModule( "A" ); // Rimuovo il modulo
		});

		$( "#reload" ).click(function() {
			Moduler.addModule( "A", a, 1 ); // Reinserisco il modulo
			Moduler.runModule( "A" ); // Eseguo il modulo
		});
	});

})( jQuery );


Torna su