私の問題の理解は、マップを切り替えようとしていることです。切り替えると、クリックイベントハンドラーがマップリンクにアタッチされます。
最初に切り替えるには、どちらが表示されているかを追跡して、適切に非表示にし、もう一方を表示できるようにします。
var unique_link = $$('#my_unique_id a'),
// keep track of which map is visible
currentMap = map1;
unique_link.addEvent('click', function(e){
// Prevent the default behavior, but still allow bubbling of events
e.preventDefault();
// Hide the current map
currentMap.setStyle('display', 'none');
// store the correct map by comparing the two maps and making it visible
currentMap = (currentMap == map1 ? map2 : map1).setStyle('display', 'block');
});
明確にするために、currentMap = (currentMap == map1 ? map2 : map1)
三項演算と呼ばれます。if / elseの省略形で、次のように書き直すことができます。
if (currentMap == map1) {
currentMap = map2;
} else {
currentMap = map1;
}
currentMap.setStyle('display', 'block');
次に、なぜ各マップのリンク上のイベントを削除する必要があるのですか?マップを切り替えるときに、それらは接続されたままになりませんでしたか?
最後に、イベントの委任とクリック時の値へのアクセスについて質問しました。これがMooToolsでどのように機能するかの例です:
// We pass an array of map1 and map2 through $$ to make sure that the returned value is an element collection
// So we can use addEvent on both elements.
// The event "type" we would have passed to addEvent has changed, using a psuedo event called "relay", which handles event delegation
// It takes a selector for matching elements
// The function that is passed to addEvent has two arugments, e, which is the event object, and element, which is the element that the
// event is being delegated to.
$$([map1, map2]).addEvent('click:relay(a)', function(e, element){
// Prevent the default behavior of the anchors
e.preventDefault();
// element argument is the anchor. So you can access it this way.
element.get('href');
// or "this" can also be used.
this.get('href');
});