Ion Vasile Ion Vasile - 4 months ago 15
Javascript Question

Prevent event to be registered multiple times JavaScript

I am using a library (javascript fullCalendar) that can be initialized with a lot of options/events.

The problem occur when I submit a form and because I need some params from one of the library event I put the submit event in the event. So I have:

var calendar = $('#calendar').fullCalendar({
..............................
dayClick: function(date, allDay, jsEvent, view) {
$("#addEvent").submit(function (event) {

//use date variable

}
});
});


First time the submit is ok, but second time the submit trigger 2x, third time the submit is triggered 3x and so . How can I handle this problem? I was thinking to make a function but each time I call the function the submit event is registered and same problem occur.

Answer

I would recommend you not to bind the submit event handler in the dayClick event handler instead you can store the date in cache or a variable which can be used later.

var ddate;
var calendar = $('#calendar').fullCalendar({
  dayClick: function(date, allDay, jsEvent, view) {
      ddate = date; //Persist the date
  })
})


  //Event handler associate at global level
$("#addEvent").submit(function (event) {
    //use date variable
    var date = ddate;
});

As far as your current problem, You can use .off() to remove previous event handler.

    dayClick: function(date, allDay, jsEvent, view) {
        $("#addEvent").off('submit').submit(function (event) {
           //use date variable
        });
     });
Comments