jQuery beforeShowDay function
Please can someone please explain how this code works? It’s a trivial piece of code but I don’t understand/appreciate how the Option
beforeShowDay
, that calls a function works.
The DisableDates Option calls function DisableDates(date) (that seemingly) takes in a date parameter – and I can’t understand how this date parameter is being passed?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" /> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div id="date"></div> <script> $(function () { var dates = ["08/11/2020", "09/11/2020", "10/11/2020", "12/11/2020"]; $("#date").datepicker({ changeYear: true, changeMonth: true, dateFormat: "yy/mm/dd", minDate: new Date("2020/10/01"), maxDate: "+3m", beforeShowDay: DisableDates, }); function DisableDates(date) { var string = jQuery.datepicker.formatDate("dd/mm/yy", date); return [dates.indexOf(string) == -1]; } }); </script> </body> </html>
Answer
jQuery datepicker
internally calling that function and passing parameter also.
Consider below small demo where you can assign your function to another variable and use that variable to call your function with parameter.
// plugin sample code with options function demo(options) { // assign option values to plugin variables. this.date = options.date; this.beforeShowDay = options.beforeShowDay; // trigger function which invoke callback function with parameters this.triggerBeforeShowDay = function() { // as we have this.beforeShowDay = options.beforeShowDay; // below code will be same as DisableDates(this.date) this.beforeShowDay(this.date); } // return plugin object return this; } // Your callback function with parameter function DisableDates(date) { console.log(date) } // pass options values in plugin let d = new demo({ date: new Date("2020/10/01"), beforeShowDay: DisableDates }); // trigger function : Note - this part would be done internally on text change event from jquery datepicker. // For demo only we are manually calling it. d.triggerBeforeShowDay();