jQuery and .data()
I'm writing a jQuery plugin and I need to keep objects through my plugin method calls. So I tried to use .data()
as recommended here : http://docs.jquery.com/Plugins/Authoring
but I'm unable to retrieve my stored objects, here my code :
(function($) {
var methods = {
init : function(options) {
return this.each(function() {
var $this = $(this);
var geocoder = new google.maps.Geocoder();
var settings = {
'geocodeSearch': {address: 'France'}
};
// Merge default settings with user ones
if (options) {
$.extend(settings, options);
}
function drawMap(geocodeResult) {
var mapSettings = {
center: geocodeResult[0].geometry.location,
mapTypeControl: true,
mapTypeId: google.maps.MapTypeId.SATELLITE,
overviewMapControl: false,
panControl: true,
scaleControl: true,
streetViewControl: false,
zoom: 6,
zoomControl: true,
zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL }
};
var element = document.getElementById($this.attr("id"));
var map = new google.maps.Map(element, mapSettings);
var cluster = new MarkerClusterer(map);
cluster.setGridSize(100);
$this.data('eventsmap', {
c开发者_JAVA技巧luster: cluster,
map: map
});
}
geocoder.geocode(settings.geocodeSearch, drawMap);
});
},
restrictZoom : function(minimalZoom, maximalZoom) {
return this.each(function() {
var $this = $(this);
console.log($this.data());
console.log($this.data('eventsmap'));
//google.maps.event.addListener(map, 'zoom_changed', function() {
// if (map.getZoom() > maximalZoom) {
// map.setZoom(maximalZoom);
// }
// if (map.getZoom() < minimalZoom) {
// map.setZoom(minimalZoom);
// }
//});
//cluster.setMaxZoom(maximalZoom-1);
});
}
};
$.fn.eventsMap = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.eventsMap' );
}
};
})(jQuery);
When I call restrictZoom method, $this.data() (line 48) returns data from the DOM but if I try to get the 'eventsmap' attribute as set during the init method, I got undefined ($this.data('eventsmap') line 49). I'm sure it's the right DOM object and my objects are because I can see them trhough my browser debugger :
I dunno what to do.
Edited : html :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us" >
<head>
<title>Map tool | Django site admin</title>
<link rel="stylesheet" type="text/css" href="/static/admin/css/base.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/ui-darkness/jquery-ui.css" />
<!--[if lte IE 7]><link rel="stylesheet" type="text/css" href="/static/admin/css/ie.css" /><![endif]-->
<script type="text/javascript">window.__admin_media_prefix__ = "/static/admin/";</script>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.js"></script>
<script type="text/javascript" src="/static/earthquake/js/markerclusterer.js"></script>
<script type="text/javascript" src="/static/earthquake/js/map.js"></script>
<meta name="robots" content="NONE,NOARCHIVE" />
</head>
<body class="eventsmap">
<!-- Container -->
<div id="container">
<!-- Header -->
<div id="header">
<div id="branding">
<h1 id="site-name">Events database</h1>
</div>
<div id="user-tools">
Welcome,
<strong>admin</strong>.
<a href="/admin/doc/">Documentation</a> /
<a href="/admin/password_change/">
Change password</a> /
<a href="/admin/logout/">
Log out</a>
</div>
</div>
<!-- END Header -->
<div class="breadcrumbs">
<a href="/admin/">Home</a> › <a href="/admin/events">Events</a> › Map tool
</div>
<!-- Content -->
<div id="content" class="colM">
<div id="eventsmap" style="width: 100%;"></div>
<script>
$(document).ready(function() {
var mapCanvas = $("#eventsmap");
// Cleanup and prepare HTML from Django
$("#footer").remove();
$("html").height("100%");
$("body").height("100%");
$("body").css("overflow-y", "hidden");
$("#content").css('margin', 0);
mapCanvas.height($(document).height()-57);
mapCanvas.eventsMap({
geocodeSearch: {address: 'France'}
});
mapCanvas.eventsMap('restrictZoom', {
minimalZoom: 2,
maximalZoom: 9
});
});
</script>
<br class="clear" />
</div>
<!-- END Content -->
<div id="footer"></div>
</div>
<!-- END Container -->
</body>
</html>
Overall the code looks really good. But here are two ideas:
Have you tried to store a simpler object literal in that data function to ensure that to code works otherwise? You're currently storing a Google Map object and a MarkerCluster. Are those objects too complex to encode to json and store in a data attribute? (Can't remember if they are simply object literals or if they have functions and other elements in them as well)
Just a stylistic thing, but there are a number of reused names that make it harder to debug the code. (overall your code is great) There are two different variables named $this (in different scopes it looks like) and three items named eventsmap (a css class, a js variable and an extension function). While they're probably fine, it may trip up some folks reading over this code.
I hope that sparks some ideas!
I finally figured out why it didn't work, I had to ensure that plugin methods are synchronous called. To realize this, I wrap my methods in jQuery .queue function like this :
(function($) {
var methods = {
init : function(options) {
return this.each(function() {
$(this).queue(function() {
var $this = $(this), data = $this.data('eventsmap');
var geocoder = new google.maps.Geocoder();
var settings = {
'geocodeSearch': {address: 'France'}
};
// Merge default settings with user ones
if (options) {
$.extend(settings, options);
}
function drawMap(geocodeResult) {
var mapSettings = {
center: geocodeResult[0].geometry.location,
mapTypeControl: true,
mapTypeId: google.maps.MapTypeId.SATELLITE,
overviewMapControl: false,
panControl: true,
scaleControl: true,
streetViewControl: false,
zoom: 6,
zoomControl: true,
zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL }
};
var element = document.getElementById($this.attr("id"));
var map = new google.maps.Map(element, mapSettings);
var cluster = new MarkerClusterer(map);
cluster.setGridSize(100);
if (!data) {
$this.data('eventsmap', {
cluster: cluster,
map: map
});
}
$this.dequeue();
}
geocoder.geocode(settings.geocodeSearch, drawMap);
})
});
},
restrictZoom : function(args) {
var minimalZoom = args.minimalZoom;
var maximalZoom = args.maximalZoom;
return this.each(function() {
$(this).queue(function() {
var $this = $(this), data = $this.data('eventsmap');
google.maps.event.addListener(data.map, 'zoom_changed', function() {
if (data.map.getZoom() > maximalZoom) {
data.map.setZoom(maximalZoom);
}
if (data.map.getZoom() < minimalZoom) {
data.map.setZoom(minimalZoom);
}
});
data.cluster.setMaxZoom(args.maximalZoom-1);
$(this).dequeue();
});
});
}
};
$.fn.eventsMap = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.eventsMap' );
}
};
})(jQuery);
Now it works like a charm, I was calling myObject.data('eventsmap') before it was set in init method btw I'm still unable to explain why I could see the object in the browser ... :)
精彩评论