Qual padrão de design de plug-in jQuery devo usar?
Preciso criar um plugin jQuery que retorne uma única instância por ID de seletor. O plug-in deve e só será usado em elementos com id (não é possível usar o seletor que corresponda a muitos elementos); portanto, deve ser usado assim:
$('#element-id').myPlugin(options);
Preciso ter poucos métodos privados para o plug-in e poucos métodos públicos. Posso conseguir isso, mas meu principal problema é que quero obter a mesma instância sempre que chamo $ ('# element-id'). MyPlugin ().E eu quero ter algum código que deve ser executado apenas na primeira vez em que o plug-in é inicializado para um determinado ID (construçãoOoptions
parâmetro @ deve ser fornecido na primeira vez, para a construção, depois disso não quero que a construção seja executada, para que eu possa acessar o plug-in como $ ('# element-id'). myPlugin () O plug-in deve ser capaz de trabalhar com vários elementos (geralmente até 2) na mesma página (mas cada um deles precisará de sua própria configuração, novamente - eles serão inicializados por ID, não por seletor de classe comum, por exemplo) . A sintaxe acima é apenas um exemplo - estou aberto a sugestões sobre como atingir esse padrãoTenho alguma experiência em OOP com outra linguagem, mas conhecimento limitado de javascript e estou realmente confuso sobre como fazê-lo corretament
EDITA
Para elaborar - este plug-in é um wrapper de API do GoogleMaps v3 (auxiliar) para me ajudar a me livrar da duplicação de código, pois uso o google maps em muitos lugares, geralmente com marcadores. Esta é a biblioteca atual (muito código removido, apenas os métodos mais importantes são deixados de ver):
;(function($) {
/**
* csGoogleMapsHelper set function.
* @param options map settings for the google maps helper. Available options are as follows:
* - mapTypeId: constant, http://code.google.com/apis/maps/documentation/javascript/reference.html#MapTypeId
* - mapTypeControlPosition: constant, http://code.google.com/apis/maps/documentation/javascript/reference.html#ControlPosition
* - mapTypeControlStyle: constant, http://code.google.com/apis/maps/documentation/javascript/reference.html#MapTypeControlStyle
* - mapCenterLatitude: decimal, -180 to +180 latitude of the map initial center
* - mapCenterLongitude: decimal, -90 to +90 latitude of the map initial center
* - mapDefaultZoomLevel: integer, map zoom level
*
* - clusterEnabled: bool
* - clusterMaxZoom: integer, beyond this zoom level there will be no clustering
*/
$.fn.csGoogleMapsHelper = function(options) {
var id = $(this).attr('id');
var settings = $.extend(true, $.fn.csGoogleMapsHelper.defaults, options);
$.fn.csGoogleMapsHelper.settings[id] = settings;
var mapOptions = {
mapTypeId: settings.mapTypeId,
center: new google.maps.LatLng(settings.mapCenterLatitude, settings.mapCenterLongitude),
zoom: settings.mapDefaultZoomLevel,
mapTypeControlOptions: {
position: settings.mapTypeControlPosition,
style: settings.mapTypeControlStyle
}
};
$.fn.csGoogleMapsHelper.map[id] = new google.maps.Map(document.getElementById(id), mapOptions);
};
/**
*
*
* @param options settings object for the marker, available settings:
*
* - VenueID: int
* - VenueLatitude: decimal
* - VenueLongitude: decimal
* - VenueMapIconImg: optional, url to icon img
* - VenueMapIconWidth: int, icon img width in pixels
* - VenueMapIconHeight: int, icon img height in pixels
*
* - title: string, marker title
* - draggable: bool
*
*/
$.fn.csGoogleMapsHelper.createMarker = function(id, options, pushToMarkersArray) {
var settings = $.fn.csGoogleMapsHelper.settings[id];
markerOptions = {
map: $.fn.csGoogleMapsHelper.map[id],
position: options.position || new google.maps.LatLng(options.VenueLatitude, options.VenueLongitude),
title: options.title,
VenueID: options.VenueID,
draggable: options.draggable
};
if (options.VenueMapIconImg)
markerOptions.icon = new google.maps.MarkerImage(options.VenueMapIconImg, new google.maps.Size(options.VenueMapIconWidth, options.VenueMapIconHeight));
var marker = new google.maps.Marker(markerOptions);
// lets have the VenueID as marker property
if (!marker.VenueID)
marker.VenueID = null;
google.maps.event.addListener(marker, 'click', function() {
$.fn.csGoogleMapsHelper.loadMarkerInfoWindowContent(id, this);
});
if (pushToMarkersArray) {
// let's collect the markers as array in order to be loop them and set event handlers and other common stuff
$.fn.csGoogleMapsHelper.markers.push(marker);
}
return marker;
};
// this loads the marker info window content with ajax
$.fn.csGoogleMapsHelper.loadMarkerInfoWindowContent = function(id, marker) {
var settings = $.fn.csGoogleMapsHelper.settings[id];
var infoWindowContent = null;
if (!marker.infoWindow) {
$.ajax({
async: false,
type: 'GET',
url: settings.mapMarkersInfoWindowAjaxUrl,
data: { 'VenueID': marker.VenueID },
success: function(data) {
var infoWindowContent = data;
infoWindowOptions = { content: infoWindowContent };
marker.infoWindow = new google.maps.InfoWindow(infoWindowOptions);
}
});
}
// close the existing opened info window on the map (if such)
if ($.fn.csGoogleMapsHelper.infoWindow)
$.fn.csGoogleMapsHelper.infoWindow.close();
if (marker.infoWindow) {
$.fn.csGoogleMapsHelper.infoWindow = marker.infoWindow;
marker.infoWindow.open(marker.map, marker);
}
};
$.fn.csGoogleMapsHelper.finalize = function(id) {
var settings = $.fn.csGoogleMapsHelper.settings[id];
if (settings.clusterEnabled) {
var clusterOptions = {
cluster: true,
maxZoom: settings.clusterMaxZoom
};
$.fn.csGoogleMapsHelper.showClustered(id, clusterOptions);
var venue = $.fn.csGoogleMapsHelper.findMarkerByVenueId(settings.selectedVenueId);
if (venue) {
google.maps.event.trigger(venue, 'click');
}
}
$.fn.csGoogleMapsHelper.setVenueEvents(id);
};
// set the common click event to all the venues
$.fn.csGoogleMapsHelper.setVenueEvents = function(id) {
for (var i in $.fn.csGoogleMapsHelper.markers) {
google.maps.event.addListener($.fn.csGoogleMapsHelper.markers[i], 'click', function(event){
$.fn.csGoogleMapsHelper.setVenueInput(id, this);
});
}
};
// show the clustering (grouping of markers)
$.fn.csGoogleMapsHelper.showClustered = function(id, options) {
// show clustered
var clustered = new MarkerClusterer($.fn.csGoogleMapsHelper.map[id], $.fn.csGoogleMapsHelper.markers, options);
return clustered;
};
$.fn.csGoogleMapsHelper.settings = {};
$.fn.csGoogleMapsHelper.map = {};
$.fn.csGoogleMapsHelper.infoWindow = null;
$.fn.csGoogleMapsHelper.markers = [];
})(jQuery);
uso é parecido com este (não exatamente exatamente assim, porque existe um wrapper PHP para automatizá-lo com uma chamada, mas basicamente
$js = "$('#$id').csGoogleMapsHelper($jsOptions);\n";
if ($this->venues !== null) {
foreach ($this->venues as $row) {
$data = GoogleMapsHelper::getVenueMarkerOptionsJs($row);
$js .= "$.fn.csGoogleMapsHelper.createMarker('$id', $data, true);\n";
}
}
$js .= "$.fn.csGoogleMapsHelper.finalize('$id');\n";
echo $js;
Os problemas da implementação acima são que eu não gosto de manter um mapa de hash para "settings" e "maps"
O$id
é o ID do elemento DIV em que o mapa é inicializado. É usado como chave nos mapas .map e .settings, onde eu mantenho as configurações e a instância do GoogleMaps MapObject para cada GoogleMaps inicializado na página. O$jsOptions
e$data
do código PHP são objetos JSON.
Agora preciso criar uma instância do GoogleMapsHelper que possua suas próprias configurações e o objeto de mapa do GoogleMaps, para que depois de inicializá-lo em determinado elemento (por seu ID), possa reutilizar essa instância. Mas se eu inicializá-lo com N elementos na página, cada um deles deve ter configuração própria, objeto de mapa et
Não insisto que isso seja implementado como um plugin jQuery! Eu insisto que seja flexível e extensível, porque o utilizarei em um grande projeto com mais de uma dúzia de telas diferentes atualmente planejadas, onde será usada em alguns meses, pois alterar a interface de uso seria um pesadelo para refatorar todo o projeto .
Vou adicionar uma recompensa por isso.