Si possono aggiungere funzioni al namespace JQuery che in fin dei conti è un oggetto
Il codice di un Plugin va inserito in un file con questo nome: jQuery.myPlugin.js
Javascript code:
jQuery.foo = function() {
alert('This is a test. This is only a test.');
};
A questo punto posso chiamare la mia funzione anche così: $.foo(), praticamente all'interno del namespace di JQuery che è un prefisso che serve a circoscrivere la definizione delle funzioni ad un certo dominio affinchè non ci siano conflitti con altre librerie per es.
Rimane comunque il problema di conflitto nel caso utilizzassi più plugins con definite le stesse funzioni.
Potrei risolvere in questo modo:
Javascript code:
jQuery.myPlugin = {
foo: function() {
alert('This is a test. This is only a test.');
},
bar: function(param) {
alert('This function takes a parameter, which is "' + param + '".');
}
};
Finora abbiamo fatto dei metodi statici, cioè applicati all'oggetto JQuery. Ma molto più utile sarebbe avere dei metodi d'istanza, cioè che si possano chiamare su ogni elemento del DOM. Per fare ciò bisogna estendere l'oggetto JQuery.fn che è un alias per JQuery.prototype
Javascript code:
jQuery.fn.xyzzy = function() {
alert('Nothing happens.');
}
$('div').xyzzy();
Se ricordate abbiamo detto che la funzione $() recuper uno o l'array di elementi, dunque un metodo teoricamente deve essere chiamato su ogni elemento per mantenere la consistenza con la libreria JQuery. Per questo usiamo l'implicit iteration:
Javascript code:
jQuery.fn.showAlert = function() {
this.each(function() {
alert('You called this method on "' + this + '".');
});
}
Abbiamo detto inoltre che ogni metodo JQuery restituisce l'oggetto cui è applicato (method chaining). Dunque scriveremo:
Javascript code:
jQuery.fn.showAlert = function() {
return this.each(function() {
alert('You called this method on "' + this + '".');
});
}
$('div').showAlert().hide('slow');
Adesso facciamo un vero metodo che serve a recuperare il padre di un elemento:
Javascript code:
jQuery.fn.grandparent = function() {
var grandparents = [];
jQuery.each(this, function(index, value) {
grandparents.push(value.parentNode.parentNode);
});
grandparents = $.unique(grandparents);
return this.pushStack(grandparents);
};
$(document).ready(function() {
$('.fred').grandparent().addClass('grandma').end().addClass('grandson');
});
Analizziamo il codice:
var grandparents = [];
jQuery.each(this, function(index, value) {
grandparents.push(value.parentNode.parentNode);
});Creo un array e ci metto dentro tutti i padri
grandparents = $.unique(grandparents);
Elimino i doppioni
return this.pushStack(grandparents);
pushStack() è un metodo per settare l'array dei padri senza distruggere l'oggetto e permette inoltre di usare il metodo end() per tornare all'elemento precdente nella catena
Molto utile è passare i parametri ad una funzione in questo modo:
Javascript code:
jQuery.fn.myMethod= function(parameters) {
defaults = {
aString: 'goodbye',
aNumber: 97
};
jQuery.extend(defaults, parameters);
alert('The string is "' + defaults.aString + '" The number is "' + defaults.aNumber + '"');
}
$(document).ready(function() {
$('div').myMethod({aString: 'hello', aNumber: 52});
$('div').myMethod({aString: 'hello'});
$('div').myMethod({aNumber: 52});
$('div').myMethod();
});
Analizziamo il codice:
defaults = {
aString: 'goodbye',
aNumber: 97
};
jQuery.extend(defaults, parameters);Passo una hash di parametri. Il metodo extend aggiunge proprietà all'oggetto JQuery, così posso avere dei valori di default da sovrascrivere
Creiamo degli shortcut per alcune funzioni custom che effettuino delle transizioni:
Javascript code:
jQuery.fn.slideFadeOut = function(speed, callback) {
return this.animate({height: 'hide', opacity: 'hide'}, speed, callback);
}
jQuery.fn.slideFadeIn = function(speed, callback) {
return this.animate({height: 'show', opacity: 'show'}, speed, callback);
}
$(document).ready(function() {
var alertDiv = function(event) {
$(this).slideFadeIn(1000);
}
$('div').each(function () {
$context = $(this);
$context.slideFadeOut(1000, alertDiv);
})
});