1
\$\begingroup\$

I have created an app, which show chart, table detail of chart, with filter date. I created app with Backbone and Marionette, chart with Chartist.js, and the filter date I'm using Pikaday.js and Moment.js just to simplify date handling.

One important thing, I'm using jQuery too, but sometimes in my script I use function from jQuery, and native Javascript. For example sometimes I use addEventListener('change') and on('change')

It's not given error, but I want ask is there a problem for call two function on jQuery and native Javascript at same times? And my code is very dirty and DRY, can you give me a suggestion for better script? or there's another shorter way or shorter code than my script?

This is filter controller which have dirty and dry code chart_controller.js

programming.module("Program.Chart",function(Chart, programming, Backbone, Marionette, $, _){
    Chart.Controller = {
        getData : function(){

            var data1 = programming.request("data:entities");
            var total = programming.request("data:total");

            if(data1 !== undefined){
                var filteredData = programming.Program.FilteredCollection({
                    collection : data1,
                    filterFunction : function(criterion){
                        return function(data){
                            var dateModel = moment(data.get("tanggal"),'DD/MM/YYYY');
                            var startDate = moment(criterion.date1,'DD/MM/YYYY')
                            var endDate = moment(criterion.date2,'DD/MM/YYYY')

                            if(dateModel.isSameOrAfter(startDate)){
                                if(dateModel.isSameOrBefore(endDate)){
                                    return data 
                                }
                            }
                        }
                    }
                })


                filterPanel = new Chart.filterPanel({
                    templateHelpers : function(){
                        return {
                            warnmessage : "Tidak ada transaksi untuk saat ini"
                        }
                    }
                })
                chartLayout = new Chart.chartLayout()
                chartPanel = new Chart.chartPanel({
                    collection: filteredData
                })
                chartDetailPanel = new Chart.chartDetailPanel({
                    collection: filteredData
                })
                chartMoreDetailPanel = new Chart.chartMoreDetailPanel({
                    collection : total
                })
                emptyView = new Chart.emptyView();

                programming.on("table:filter", function(model){
                    var period = model.get("period");
                    var format = 'DD/MM/YYYY'
                    var selectdate = $('#publicdate');
                    var dateone, datetwo

                    if(period==="Today"){
                        date1.value, dateone = moment().add('days').format(format)
                        date2.value, datetwo = moment().add('days').format(format)
                        selectdate.val('today')
                    } else if(period==="Yesterday"){
                        date1.value, dateone  = moment().add(-1,'days').format(format)
                        date2.value, datetwo = moment().add(-1,'days').format(format)
                        selectdate.val('yesterday')
                    } else if(period==="This Month"){
                        date1.value, dateone  = moment().add('month').startOf('month').format(format)
                        date2.value, datetwo = moment().add('month').endOf('month').format(format)
                        selectdate.val('thismonth')
                    } else if(period==="Last Month"){
                        date1.value, dateone  = moment().add(-1,'month').startOf('month').format('DD/MM/YYYY')
                        date2.value, datetwo = moment().add(-1,'month').endOf('month').format('DD/MM/YYYY')
                        selectdate.val('lastmonth')
                    }

                    if(period!=="All Of Time"){
                    window.scrollTo(0,0)
                    var filter = {
                        date1 : dateone,
                        date2 : datetwo
                    }
                    filterPanel.trigger("form:filter", filter)
                    }
                })


                filterPanel.on("form:filter", function(data){
                    var criterion = data
                    filteredData.filter(criterion)
                    data1 = filteredData.filter(criterion)
                    if(data1.length === 0){
                        chartPanel.trigger("chart:remove")
                        $('.warn').stop(true, false).slideDown(80,function(){
                            setTimeout(function(){$('.warn').stop(true, false).slideUp(80)},3000)
                        })
                    } else {
                        $('.statistic').fadeOut(100,function(){
                           chartPanel.trigger("chart:render")
                           $('.statistic').fadeIn(100) 
                        })
                    }
                })

                var firstFilter = {
                    date1 : moment().add('month').startOf('month'),    
                    date2 : moment().add('month').endOf('month')  
                }



                filterPanel.trigger("form:filter" ,firstFilter)

                filterPanel.on("filter:render", function(){
                    //DatePicker
                    var format = "DD/MM/YYYY"

                    var date1 = new Pikaday({
                            field : $("#date1",this.el)[0],
                            format : format
                        })
                    $("#date1",this.el)[0].value = moment().add('month').startOf('month').format(format)

                    var date2 = new Pikaday({
                        field : $("#date2",this.el)[0],
                        format : format
                    })
                    $("#date2",this.el)[0].value = moment().add('month').endOf('month').format(format)


                    var selectdate = $('#publicdate',this.el)[0];
                    selectdate.addEventListener("change",function(){
                        var value = selectdate.value;
                        var date1 = $('#date1',this.el)[0];
                        var date2 = $('#date2',this.el)[0];
                        var publicdate = $('#publicdate')
                        if(value==="today"){
                            date1.value = moment().add('days').format(format)
                            date2.value = moment().add('days').format(format)
                            date1.onchange = function(){
                                publicdate.val('custom')
                            }
                            date2.onchange = function(){
                                publicdate.val('custom')
                            }
                        } else if(value==="yesterday"){
                            date1.value = moment().add(-1,'days').format(format)
                            date2.value = moment().add(-1,'days').format(format)
                            date1.onchange = function(){
                                publicdate.val('custom')
                            }
                            date2.onchange = function(){
                                publicdate.val('custom')
                            }
                        } else if(value==="thismonth"){
                            date1.value = moment().add('month').startOf('month').format(format)
                            date2.value = moment().add('month').endOf('month').format(format)
                            date1.onchange = function(){
                                publicdate.val('custom')
                            }
                            date2.onchange = function(){
                                publicdate.val('custom')
                            }
                        } else if(value==="lastmonth"){
                            date1.value = moment().add(-1,'month').startOf('month').format('DD/MM/YYYY')
                            date2.value = moment().add(-1,'month').endOf('month').format('DD/MM/YYYY')
                            date1.onchange = function(){
                                publicdate.val('custom')
                            }
                            date2.onchange = function(){
                                publicdate.val('custom')
                            }
                        }
                    })
                })

                chartPanel.on("chart:render",function(){
                    //Chartist JS           
                    var tanggal = []
                    var label = data1.models.map(function(model,index){
                        return model.get("tanggal")
                    })

                    function unique(list) {
                        var result = [];
                        $.each(list, function(i, e) {
                            if ($.inArray(e, result) == -1) result.push(e);
                        });
                        return result;
                    }

                    var labels = unique(label)

                    var tshirtv = [];
                    var casev = [];  
                    var tanggal = [];

                    var series = data1.models.map(function(model,index){
                        tanggal[index] = model.get("tanggal");

                        if(tanggal[index - 1] === model.get("tanggal")){
                            if(model.get("produk")==="T-Shirt"){
                                tshirtv[index - 1] = model.get("jumlah");
                            } else if(model.get("produk")==="Case"){
                                casev[index - 1] = model.get("jumlah");
                            }
                        } else {
                            if(model.get("produk")==="T-Shirt"){
                                tshirtv[index] = model.get("jumlah");
                                casev[index] ="0";
                            } else if(model.get("produk")==="Case"){
                                casev[index] = model.get("jumlah");
                                tshirtv[index] ="0";
                            }
                        }
                    })

                    tshirtv = tshirtv.filter(()=>true)
                    casev = casev.filter(()=>true)

                    if((tshirtv.length !== 1) && (casev.length !== 1))  {
                        var series = [
                            {
                                name : "T-shirt",
                                data : tshirtv
                            },
                            {
                                name : "Case",
                                data : casev
                            }
                        ]
                        //Line Chart
                        var data = {
                            labels : labels,
                            series : series
                        }
                        var option = {
                            showArea : true,
                            lineSmooth : false,
                            showPoint : true,
                            chartPadding : {
                                bottom:60,
                                top:60,
                            },
                            axisX : {
                                showGrid:false,
                            },
                            axisY : {  
                                onlyInteger : true,
                            },  
                            plugins : [
                                Chartist.plugins.ctAxisTitle({
                                    axisX: {
                                       axisClass: 'ct-axis-title',
                                       offset: {
                                          x: 0,
                                          y: 50
                                       },
                                       textAnchor: 'middle'
                                    },
                                    axisY: {
                                       axisTitle: 'Jumlah Penjualan',
                                       axisClass: 'ct-axis-title',
                                       offset: {
                                          x: 0,
                                          y: 0
                                       },
                                       textAnchor: 'middle',
                                       flipTitle: false
                                     }
                                }),
                                Chartist.plugins.ctPointLabels({
                                    textAnchor : "middle"
                                }),
                                Chartist.plugins.legend()
                            ]
                        }

                        var responsiveOptions = [
                          [
                              'screen and (max-width: 640px)', {
                                showLine: false,
                                showPoint : true,
                                axisX: {
                                  labelInterpolationFnc: function(value) {
                                    return value.substr(0,2);
                                  }
                                }
                              }
                          ],
                          [
                              'screen and (max-width: 360px)', {
                                showLine: false,
                                showPoint : true,
                                height:"100%",
                                axisX: {
                                  labelInterpolationFnc: function(value) {
                                    return value.substr(0,2);
                                  }
                                }
                              }
                          ]
                        ];


                        new Chartist.Line($('.statistic',this.el)[0],data,option,responsiveOptions)
                    } else {
                        //Donut Chart
                        var data2 = {
                            labels : ['T-Shirt', 'Case'],
                            series : [tshirtv[0], casev[0]]
                        }
                        var option2 = { 
                            chartPadding : {
                                top : 0,  
                            },
                            labelInterpolationFnc : function(value,series){
                                return value + ": " +data2.series[series].value
                            },
                            donut:true,
                            donutWidth : 60,
                            plugins : [
                                Chartist.plugins.legend()
                            ]
                        }
                        new Chartist.Pie($('.statistic',this.el)[0],data2,option2)
                    }

                })

                chartPanel.on("chart:remove", function(){
                   $('.statistic').fadeOut(100)
                })

                chartPanel.on("chart:total", function(){
                    var a = {
                        totalTshirt : 12,
                        totalCase : 34,
                    }
                    return a
                })

                chartLayout.on("show", function(){
                    chartLayout.filterRegion.show(filterPanel)
                    chartLayout.chartRegion.show(chartPanel)
                    chartLayout.detailRegion.show(chartDetailPanel)
                    chartLayout.moreDetailRegion.show(chartMoreDetailPanel)
                })

                programming.wrapper.show(chartLayout)

            } else {
                chartPanel = new Chart.notfound()

                programming.wrapper.show(chartPanel)
            }


        }
    }
})

And this too chart.js

programming.module("Program", function(Program, programming, Backbone, Marionette, $, _){
    Program.salesM = Backbone.Model.extend({})

    Program.salesC = Backbone.Collection.extend({
        model : Program.salesM,
        comparator : function(item){
            return [item.get("tanggal"), item.get("produk"), item.get("jumlah")]
        }
    })

    Program.totalM = Backbone.Model.extend({})
    Program.totalC = Backbone.Collection.extend({
        model : Program.totalM
    })

    var data, total;
    var initializeData = function(){
        data = new Program.salesC([
            {
                id : "1",
                tanggal : "01/07/2016",
                produk : "T-Shirt",
                jumlah : "33"
            },
            {
                id : "2",
                tanggal : "01/07/2016",
                produk : "Case",
                jumlah : "9"
            },
            {
                id : "3",
                tanggal : "02/07/2016",
                produk : "T-Shirt",
                jumlah : "30"
            },
            {
                id : "4",
                tanggal : "02/07/2016",
                produk : "Case",
                jumlah : "12"
            },
            {
                id : "5",
                tanggal : "03/07/2016",
                produk : "T-Shirt",
                jumlah : "12"
            },
            {
                id : "6",
                tanggal : "03/07/2016",
                produk : "Case",
                jumlah : "44"
            },
            {
                id : "7",
                tanggal : "04/08/2016",
                produk : "T-Shirt",
                jumlah : "33"
            },
            {
                id : "8",
                tanggal : "04/08/2016",
                produk : "Case",
                jumlah : "42"
            },
            {
                id : "9",
                tanggal : "05/08/2016",
                produk : "T-Shirt",
                jumlah : "13"
            },
            {
                id : "10",
                tanggal : "05/08/2016",
                produk : "Case",
                jumlah : "34"
            },
            {
                id : "11",
                tanggal : "06/08/2016",
                produk : "T-Shirt",
                jumlah : "4"
            },
            {
                id : "12",
                tanggal : "06/08/2016",
                produk : "Case",
                jumlah : "34"
            },
            {
                id : "13",
                tanggal : "07/08/2016",
                produk : "T-Shirt",
                jumlah : "56"
            },
            {
                id : "14",
                tanggal : "07/08/2016",
                produk : "Case",
                jumlah : "44"
            },
            {
                id : "15",
                tanggal : "08/08/2016",
                produk : "T-Shirt",
                jumlah : "56"
            },
            {
                id : "16",
                tanggal : "08/08/2016",
                produk : "Case",
                jumlah : "29"
            },
            /*
            {
                id : "17",
                tanggal : "09/08/2016",
                produk : "T-Shirt",
                jumlah : "54"
            },
            */
            /*
            {
                id : "18",
                tanggal : "09/08/2016",
                produk : "Case",
                jumlah : "19"
            },
            */
            {
                id : "19",
                tanggal : "10/08/2016",
                produk : "T-Shirt",
                jumlah : "19"
            },
            {
                id : "20",
                tanggal : "10/08/2016",
                produk : "Case",
                jumlah : "12"
            },
        ])
    }

    var initializeTotal = function(){
        var todtshirt = 0;
        var yestshirt = 0;
        var tmontshirt = 0;
        var lmontshirt = 0;
        var alloftimetshirt = 0;
        var todcase = 0;
        var yescase = 0;
        var tmoncase = 0;
        var lmoncase = 0;
        var lmoncase = 0;
        var alloftimecase = 0;

        data.models.map(function(model, index){
            var format      = 'DD/MM/YYYY'
            var tanggal     = moment(model.get("tanggal"), format)
            var today       = moment(moment().add('days').startOf("day"), format)
            var yesterday   = moment(moment().add(-1,'days').startOf("day"), format)
            var thismonthS  = moment(moment().add('month').startOf('month'), format)
            var thismonthE  = moment(moment().add('month').endOf('month'), format)
            var lastmonthS  = moment(moment().add(-1,'month').startOf('month'), format)
            var lastmonthE  = moment(moment().add(-1,'month').endOf('month'), format)

            if(model.get("produk")==="T-Shirt"){
                alloftimetshirt += parseInt(model.get("jumlah"))
            } else if(model.get("produk")==="Case"){
                alloftimecase += parseInt(model.get("jumlah"))
            }

            if(tanggal.isSame(today)){
                if(model.get("produk")==="T-Shirt"){
                    todtshirt += parseInt(model.get("jumlah"))
                } else if(model.get("produk")==="Case"){
                    todcase += parseInt(model.get("jumlah"))
                }
            }

            if(tanggal.isSameOrAfter(yesterday)){
                if(model.get("produk")==="T-Shirt"){
                    yestshirt += parseInt(model.get("jumlah"))
                } else if(model.get("produk")==="Case"){
                    yescase += parseInt(model.get("jumlah"))
                }
            }

            if(tanggal.isSameOrAfter(thismonthS)){
                if(tanggal.isSameOrBefore(thismonthE)){
                    if(model.get("produk")==="T-Shirt"){
                        tmontshirt += parseInt(model.get("jumlah"))
                    } else if(model.get("produk")==="Case"){
                        tmoncase += parseInt(model.get("jumlah"))
                    }
                }
            }

            if(tanggal.isSameOrAfter(lastmonthS)){
                if(tanggal.isSameOrBefore(lastmonthE)){
                    if(model.get("produk")==="T-Shirt"){
                        lmontshirt += parseInt(model.get("jumlah"))
                    } else if(model.get("produk")==="Case"){
                        lmoncase += parseInt(model.get("jumlah"))
                    }
                }
            }
        })

        total = new Program.totalC([
            {
                id : "1",
                period : "Today",
                totaltshirt : todtshirt,
                totalcase : todcase,
                total : todtshirt + todcase
            },
            {
                id : "2",
                period : "Yesterday",
                totaltshirt : yestshirt,
                totalcase : yescase,
                total : yestshirt + yescase
            },
            {
                id : "3",
                period : "This Month",
                totaltshirt : tmontshirt,
                totalcase : tmoncase,
                total : tmontshirt + tmoncase
            },
            {
                id : "4",
                period : "Last Month",
                totaltshirt : lmontshirt,
                totalcase : lmoncase,
                total : lmontshirt + lmoncase
            },
            {
                id : "5",
                period : "All Of Time",
                totaltshirt : alloftimetshirt,
                totalcase : alloftimecase,
                total : alloftimetshirt + alloftimecase
            }
        ])
    }

    var API = {
        getData : function(){
            if(data===undefined){
                initializeData();
            }
            return data;
        },
        getTotal : function(){
            if(total===undefined){
                initializeTotal();
            }
            return total;
        }
    }

    programming.reqres.setHandler("data:entities", function(){
        return API.getData();
    })

    programming.reqres.setHandler("data:total", function(){
        return API.getTotal();
    })
})
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.