Plugin jQuery: creare un metodo per gestire le opzioni

Plugin jQuery: creare un metodo per gestire le opzioni

Nei nostri plugin jQuery possiamo fornire un metodo pubblico per gestire le opzioni.

Il nostro metodo funzionerĂ  come un getter/setter:


"use strict";

$.fn.hilight = function( options ) {

    var opts = $.extend( {}, $.fn.hilight.defaults, options );

    $.fn.hilight.defaults = {
		   foreground: "black",
		   background: "yellow"
	  };

    $.fn.hilight.option = function( name, value ) {
        name = name || false;
        value = value || false;

        if( !name ) { // Non può funzionare senza il nome di un'opzione
            console.warn( "Option name missing" );
            return;
        }
        if( !value ) {
            if( opts.hasOwnProperty( name ) ) { // Deve essere un'opzione valida
                return opts[name];
            } else {
                console.warn( "Option " + name + " does not exist" );
                return;
            }
        } else {
            if( opts.hasOwnProperty( name ) ) {
                opts[name] = value;
            } else {
                console.warn( "Option " + name + " does not exist" );
                return;
            }
        }
        
    };

};

Esempio d'uso:


"use strict";

var $hilight = $( "#test" ).hilight();
var bg = $hilight.option( "background" ); // "yellow"

$hilight.option( "foreground", "red" );

Torna su