Vahe Vahe - 17 days ago 4
Javascript Question

JS Closure - Multiple date picker initializations / invocations that relies on callback

How do I properly invoke and initialize multiple datepickers (Bootstrap date picker) on the following script using a closure so that I will not have to duplicate my functions for each date picker id?

http://www.daterangepicker.com/ is the picker I am using

cb_helper <---- This is where I tried to use a closure unsuccessfully so that I will "remember" the id passed in...

What am I doing wrong?

JS

$(function() {
var start = moment().subtract(29, 'days');
var end = moment();
var idVal = "";
function cb(start, end) {
$(idVal + ' span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}



function cb_helper(id, start, end)
{
(function(){
idVal = id;
cb(start, end);
})();
}

function init(id){
$(id).daterangepicker({
startDate: start,
endDate: end,
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb);
}

init("#reportrange_profitability");
init("#reportrange_volume");
cb_helper("#reportrange_profitability", start, end);
cb_helper("#reportrange_volume", start, end);
});

Answer
$(function() {
    var start = moment().subtract(29, 'days');
    var end = moment();


    function cb(idVal) {
        return function(start, end) {
            $(idVal + ' span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
        }
    }


    function init(id, start, end) {
        $(id).daterangepicker({
            startDate: start,
            endDate: end,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        }, cb(id));
    }

    init("#reportrange_profitability", start, end);
    init("#reportrange_volume", start, end);
});
Comments