0

我々が持っていると仮定すると:カレンダーが更新されるとJavascriptのイベントリスナーの問題

//Some vars 

function initialSetup(date){ 
    // Call to some functions 
} 

function populateCalendar(date){ 
    // Call to several function. Task : build and populate a calendar with the date 

    awesomeFunction() // Have to set click event listener 

    // If the function call purpose was detected as an update, return value 
} 

function awesomeFunction(){ 
    // For each day in the calendar, if there is a click, set the displayed date as the correct month, then rebuild the calendar 
    $(".notInTheMonth").each(function(){ 
     $(this).click(function(e){ 
      //Some process 
      //Changing date 
      populateCalendar(processedDate) 
      updateCalendar(processedVar)  
      //Some another process 
     }); 
    }); 
} 

function updateCalendar(updated){ 
    // Jquery transition from the old calendar to the new 
    // Will put the content of the updated var to replace the content in the table calendar 
} 

、イベントは置き換えられませんので、カレンダーのクリックイベントの後に、それは1時間を更新しますが、reputません。 awesomeFunctionによって提供されるイベントリスナー

何が問題なのですか?

答えて

2

あなたはイベントの委任を使用することができます:あなたが要素にイベントリスナーを添付すると

$(document).on('click', '.notInTheMonth', function() { 
    // Your event handler here 
}); 

、リスナーがいる限り、この要素がDOMに存在しているとして存在します。したがって、カレンダーを更新すると、これらの要素が削除されるため、イベントリスナーも削除されます。イベントの委任で

、あなたが指定した要素の型

チェックthis(クラスnotInTheMonth持つ任意の要素)から任意のバブリングイベントを聴くための責任があるデリゲート(文書などの静的要素)を設定しています

EDIT

カレンダーとセットイベントリスナーを構築する場合、すべての時間は、カレンダーは、それがプロセスを構築して、イベントリスナーを添付しています完了したことを確認してください。

1)カレンダー

2)カレンダー要素がDOMに存在して、リスナーの違いを何

+0

を添付していることを確認してくださいを作りますか? –

+0

@NicolasFrbezar:https://learn.jquery.com/events/event-delegation/ – Fidel90

+0

はい、しかし、私のコードでは、同じ話、いいえ?クリックがあると、新しいカレンダーが作成され、各項目にイベントリスナーが設定され、jqueryアニメーションの後に、新しい要素に新しいイベントリスナーが追加されます。 –