Reputation: 1312
I have a bunch of markers in an index page
which I create and register listeners to them in a loop. I click on one of those markers and it takes me to next page
where I have an anchor button
that needs to know which marker initiated the action. I am having a following scenario step wise:
//outputs a correct id 1 in console
//outputs a correct id 1 in console on clicking anchor
//outputs a correct id 2 in console
//outputs both ids 1 and 2 in console on clicking anchor
The last step is where the problem is where I just want id 2
. In fact if I repeat the process the third time, I get all the ids 1, 2 and 3 while I want just the id 3
in this case.
My code:
$.each(otherLocations, function(index, value){
var markerOtherLocations = new MarkerWithLabel({
position: new google.maps.LatLng(value.latitude, value.longitude),
map: map,
title: value.name+" "+value.distance,
icon: iconImage,
labelContent: value.name+" "+value.distance,
labelAnchor: new google.maps.Point(50, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.60}
});
google.maps.event.addListener(markerOtherLocations, 'click', function() {
$.mobile.changePage("#detail-page", { transition: "flip"} );
console.log(value.localurl);//Outputs correct url
$("#ref").on("click", function(){ //The problem is in this anchor click
console.log(value.localurl);//Outputs the current as well as all the previous urls
});
});
});
Upvotes: 0
Views: 372
Reputation: 2752
Every time when you click the markerOtherLocations, it will register a brand new onclick
event callback for #ref
which causes the problem. Remember an event can be registered by many callbacks. Consider the code below:
$("#ref").on("click", function(){
console.log('do function A');//register A first
});
$("#ref").on("click", function(){
console.log('do function B');//register B later, which won't be overridden.
});
//If you click #ref then, it'll output A and B, following the registered sequence before.
So in my opinion, your code could be:
google.maps.event.addListener(markerOtherLocations, 'click', function() {
$.mobile.changePage("#detail-page", { transition: "flip"} );
console.log(value.localurl);//Outputs correct url
$("#ref").data('origin',value.localurl);
});
$("#ref").on("click", function(){ // register once
console.log($(this).data('origin'));
});
Upvotes: 1