我有js代码,用于在某些页面上显示谷歌地图,当我想开始使用barbajs(pjax)一切都很好,直到我检查我的代码执行多次取决于我访问给定页面的次数例如:
当我访问http://example.com/regions
barba是fething我的页面包含html和js代码并执行它,第二次当我访问http://example.com/regions2
并且有类似的代码并且在控制台中我得到了我的js代码的信息执行两次,当我再次访问http://example.com/regions
代码执行3次,依此类推。我认为它的原因是我的js代码在浏览器内存中,如果它是我如何检查它的存在?或者如何使代码执行一次?
我的js代码简而言之:
Barba.Dispatcher.on('transitionCompleted', function() {
var mapDistributors = mapDistributors || {
makeMap: function() {
var loc = this.location.split(','),
pos = new google.maps.LatLng(loc[0], loc[1]);
var countryCenter = new google.maps.LatLng(59.9882184, 18.2516778);
var mapOptions = {
zoom: 6,
center: countryCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.mapObj = new google.maps.Map(document.querySelector('.mapGoogleDistributors'), mapOptions);
this.destination = pos;
var marker = new google.maps.Marker({
position: pos,
icon: 'icon.svg',
info: {
}
})
this.markers.push(marker);
},
handleRoute: function(result, status) {
if (status != google.maps.DirectionsStatus.OK || !result.routes[0]) {
alert('wrong data entered!');
return false;
}
this.pathRender.setDirections(result);
this.formInput.value = result.routes[0].legs[0].start_address;
},
prepareRoute: function(coords) {
var renderOptions = {
mapDistributors: this.mapObj,
polylineOptions: {
strokeColor: '#ff0000',
strokeWeight: 4,
strokeOpacity: 0.8
},
suppressMarkers: true
}
this.pathRender.setOptions(renderOptions);
var pathData = {
origin: coords ? coords : this.formInput.value,
destination: this.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
}
this.path.route(pathData, this.handleRoute.bind(this))
},
getGeoData: function() {
navigator.geolocation.getCurrentPosition(
function(position) {
this.prepareRoute(position.coords.latitude + "," + position.coords.longitude);
}.bind(this),
function(errorObj) {
alert('error!');
}, {
enableHighAccuracy: true
}
);
},
checkGeoSupport: function() {
if (navigator.geolocation) {
var findPositionButton = document.querySelector('#findButton');
findPositionButton.classList.remove('hidden');
findPositionButton.onclick = function(e) {
e.preventDefault();
this.getGeoData();
}.bind(this);
}
},
init: function(options) {
if (!options.location) return;
Barba.Dispatcher.on('transitionCompleted', this.makeMap.bind(this));
Barba.Dispatcher.on('transitionCompleted', this.markersLocation.bind(this));
// try { google.maps.event.addDomListener(window, "load", this.makeMap.bind(this)); } catch(e) {return; };
// try { google.maps.event.addDomListener(window, "load", this.markersLocation.bind(this)); } catch(e) {return; };
// try { google.maps.event.addDomListener(window, "load", this.showInfo.bind(this)); } catch(e) {return; };
this.options = options;
this.location = this.options.location;
this.form = document.querySelector('.mapForm');
this.formInput = document.querySelector('.inputMap');
this.path = new google.maps.DirectionsService();
this.pathRender = new google.maps.DirectionsRenderer();
console.log(this, document.querySelector('.mapForm'));
this.form.onsubmit = function(e) {
e.preventDefault();
var address = document.querySelector('#search').value;
this.getLatLng(address, 6);
}.bind(this);
this.checkGeoSupport();
},
// markers
placeMarker: function(distrybutors, instalators) {
for (var i = 0; i < distrybutors.length; i++) {
var d = distrybutors[i];
var latlng = new google.maps.LatLng(d.latLng[0], d.latLng[1]);
var marker = new google.maps.Marker({
// map: this.mapObj,
position: latlng,
icon: '/bundles/galmetmap/images/galmet_sygnet.svg',
info: {
name: d.name,
address: d.address,
phone: d.phone
}
});
this.addInfo(marker);
this.markers.push(marker);
}
this.mapClustering();
},
markers: [],
htmlInfo: function(info) {
},
//find markers
findClosest: function(position, markersToReturn) {
var positionAddress = new google.maps.LatLng(position.lat(), position.lng());
var closest = [];
var counter = 0;
mapDistributors.mapObj.setCenter(positionAddress);
mapDistributors.mapObj.setZoom(11);
for (var i = 0; i < mapDistributors.markers.length; i++) {
var marker = mapDistributors.markers[i];
var distance = mapDistributors.calcDistance(marker.position, positionAddress);
if (distance <= 150) {
var obj = {
distance: distance,
info: marker.info
}
closest.push(obj);
}
}
var chunkClosest = closest.sort(function(a, b) {
return a.distance - b.distance;
});
var results = document.querySelector('.result');
results.innerHTML = '';
for (var i = 0; i < markersToReturn; i++) {
var distance = document.createElement('div');
distance.innerHTML = 'Odległość w km ' + chunkClosest[i].distance;
var instalator = mapDistributors.htmlInfo(chunkClosest[i].info);
instalator.appendChild(distance);
results.appendChild(instalator);
}
window.location.href = "#result";
},
calcDistance: function(position1, position2) {
return (google.maps.geometry.spherical.computeDistanceBetween(position1, position2) / 1000).toFixed(2);
},
addInfo: function(marker) {
marker.addListener('click', function() {
var infowindow = new google.maps.InfoWindow({
content: mapDistributors.htmlInfo(marker.info),
});
infowindow.open(mapDistributors.mapObj, marker);
})
},
geocoder: new google.maps.Geocoder(),
getLatLng: function(address, markersToReturn) {
mapDistributors.geocoder.geocode({
'address': address
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
mapDistributors.findClosest(results[0].geometry.location, markersToReturn);
} else {
alert('reason : ' + status);
}
})
},
mapClustering: function() {
var mcOptions = {
imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'
};
this.cluster = new MarkerClusterer(this.mapObj, this.markers, mcOptions);
},
markersLocation: function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var jsonData = JSON.parse(xmlHttp.responseText);
if (jsonData.status) {
this.placeMarker(jsonData.distrybutors, jsonData.instalators);
} else {
console.log('error');
}
}
}.bind(this)
xmlHttp.open("GET", document.querySelector('#urlAdress').value, true); // true for asynchronous
xmlHttp.send();
},
}
mapDistributors.init({
location: "50.1943227,7.8434933"
});
答案 0 :(得分:0)
每次加载新页面时都会触发barba.js事件transitionCompleted
。
供您使用时,您可能会:
检查每个transitionCompleted
的当前网址/页面,检查当前页面是否正确(并最终添加控件以便不运行代码两次)。
最好的解决方案是使用Barba.js Views: http://barbajs.org/views.html