0
\$\begingroup\$

In my application display partner detail on front side using jQuery datatable. I have written JavaScript code with common declaring variable for accessing id and classes for selector.

var partnerList =
{
    urls: {
        srcPartnerList: '/partner/getpartnerlist',
        srcViewOffer: "/partner/viewoffer/",
        srcUpdateCountPartnerOffserView: "/partner/updatecountpartneroffserview",
        srcDefultLogoimage: ""
    },

    variables: {
        oTable: null,
        srchKey: 'srchParams',
        logoImageHeight: "150px",
        logoImageWidth: "150px"
    },

    controls: {
        tblPartnerList: $("#tblPartnerList"),
        searchText: "#searchText",
        btnSearch: "#btnSearch",
        divPartnerContentDetail: "#partnercontentdetail"
    },

    initDatatable: function () {
        oTable = partnerList.controls.tblPartnerList.dataTable({
            "sDom": "frtip",
            "ordering": false,
            "processing": true,
            "serverSide": true,
            "sAjaxSource": partnerList.urls.srcPartnerList,
            "aaSorting": [[0, "asc"]],
            "bLengthChange": true,
            "filter": false,
            "aoColumnDefs": [
            {
                "aTargets": [0],
                "visible": false,
            },
           {
               "aTargets": [1],
               "mRender": function (data, type, full) {
                   return partnerList.renderLogo(full[0], full[1]);
               },
               "bSortable": false
           },
           {
               "aTargets": [2],
           },
           {
               "aTargets": [3],
               "visible": true,
               "mRender": function (data, type, full) {
                   return partnerList.renderClickable(full[0]);
               },
               "bSortable": false
           }],
            "oLanguage": {
                "sEmptyTable": "No offer(s) available",
                "sLengthMenu": "Page Size: _MENU_",
                "oPaginate": {
                    "sFirst": "<<",
                    "sLast": ">>",
                    "sNext": ">",
                    "sPrevious": "<"
                }
            },
            "fnServerParams": function (aoData) {
                var srchParams = $("div").data("srchParams");
                if (srchParams) {
                    for (var i = 0; i < srchParams.length; i++) {
                        aoData.push({ "name": "" + srchParams[i].name + "", "value": "" + srchParams[i].value + "" });
                    }
                }
            }
        });
    },

    reload: function () {
        oTable.dataTable().fnClearTable(0);
        oTable.dataTable().fnStandingRedraw();
    },

    reset: function () {
        $("div").removeData(partnerList.variables.srchKey);
        partnerList.reload();
    },

    renderClickable: function (partnerID, partnerName) {
        var view = `<a title="View Offer" onclick="partnerList.partnerOfferCountView(${partnerID})" class="btn btn-xs btn-primary" href="${partnerList.urls.srcViewOffer}${partnerID}">View Offer</a>`;
        return view;
    },

    renderLogo: function (partnerID, logoUrl) {
        var image = "";
        if (logoUrl != "") {
            //"onerror="this.src=''""
            image = `<a onclick="partnerList.partnerOfferCountView(${partnerID})" href="${partnerList.urls.srcViewOffer}${partnerID}"><img src='${logoUrl}' style='height:${partnerList.variables.logoImageHeight};width:${partnerList.variables.logoImageWidth
        };'></a>`;
        }
        return image;
    }
}

My document ready function:

$(document).ready(function () {

    partnerList.initDatatable();

    $(partnerList.controls.searchText).keypress(function (e) {
        if (e.keyCode == 13) {
            if ($(this).val().trim() != '') {
                $("div").removeData(partnerList.variables.srchKey);
                $("div").data("srchParams",
                   [{ name: 'srchTxt', value: encodeURIComponent($(this).val().trim()) }]
               );
                partnerList.reload();
            }
            else {
                partnerList.reset();
            }
        }
    });

    $(partnerList.controls.btnSearch).click(function (e) {
        if ($(partnerList.controls.searchText).val().trim() != '') {
            $("div").removeData(partnerList.variables.srchKey);
            $("div").data("srchParams",
               [{ name: 'srchTxt', value: encodeURIComponent($(partnerList.controls.searchText).val().trim()) }]
           );
            partnerList.reload();
        }
        else {
            partnerList.reset();
        }
    });
});

I have written a variable partnerList and in controls add all its selectors. Is there any good way to write a script file, and any suggestions for me?

\$\endgroup\$
1
\$\begingroup\$
$(partnerList.controls.searchText)
$(partnerList.controls.btnSearch)

These two elements look like they could be part of a form. Consider using a form. This way, you can 1) hook up a submit handler and only write the handler code once and 2) you pick up both the click of the submit button and the press of the Enter key. You'll have to use preventDefault to prevent the form from actually submitting and navigating away.

$("div") is a bad way to select stuff. This affects all divs, regardless if you use it for your data table or not. Be more specific, use a class, don't blindly select all divs.

$(partnerList.controls.searchText).val().trim() is being done twice. Unless that value changes between calls for some reason, it's best you cache it in a variable instead. Same goes for $('.datatable').

$(function () {

  partnerList.initDatatable()

  const dataTables = $('.datatable')

  $(selectorToYourForm).on('submit', function (e) {
    e.preventDefault()
    const search = $(partnerList.controls.searchText).val().trim() 

    if (search != '') {
      const name = 'srchTxt'
      const value = encodeURIComponent(search)

      dataTables.removeData(partnerList.variables.srchKey)
      dataTables.data('srchParams', [{ name, value }])

      partnerList.reload()
    } else {
      partnerList.reset()
    }
  })
})
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.