【问题标题】:How to reduce repetition in Javascript code?如何减少 Javascript 代码中的重复?
【发布时间】:2022-01-23 13:09:44
【问题描述】:

我有 ASP.NET 代码,它使用 JS 作为视图的数据表。我做了一些重复的代码,因为我有 3 个表(在这种情况下)我有相同的列。只是我从控制器获得的不同数据(json)。

这是 JS 代码

<script type="text/javascript">

    function parseDate(date) {
        if (!date) {
            return ""
        }
        return new Date(parseInt(date.substr(6))).toLocaleString();
    }

    $(document).ready(function() {
        $.ajax({
            "url": "@Url.Action("GetAllByUserToday", "Dashboard")",
            "type": "GET",
            "datatype": "json",
            "success": function(res) {
                const mapped = res.data.map((dt) => {
                    return {
                        ...dt,
                        CreatedDate: parseDate(dt.CreatedDate),
                        Status: dt.Status ? "Sukses" : "Gagal",
                        IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                    };
                });

                $("#getAllToday").DataTable({
                    "data": mapped,
                    "dom": 'Bfrtip',
                    "buttons": ['copy', 'excel'],
                    "columns": [
                        { "data": "Nama" },
                        { "data": "NoHP" },
                        { "data": "Content" },
                        { "data": "Sender" },
                        { "data": "IsUsingTemplate" },
                        { "data": "Status" },
                        { "data": "CreatedDate" }
                    ],
                    columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                    order: [0, 'desc'],
                });
            }
        });

        $("#getAll_wrapper").addClass("w-100");

    });

    $(document).ready(function() {
        $.ajax({
            "url": "@Url.Action("GetAllSentByUserToday", "Dashboard")",
            "type": "GET",
            "datatype": "json",
            "success": function(res) {
                const mapped = res.data?.map((dt) => {
                    return {
                        ...dt,
                        CreatedDate: parseDate(dt.CreatedDate),
                        Status: dt.Status ? "Sukses" : "Gagal",
                        IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                    };
                });


                $("#getAllSentToday").DataTable({
                    "data": mapped,
                    "dom": 'Bfrtip',
                    "buttons": ['copy', 'excel'],
                    "columns": [
                        { "data": "Nama" },
                        { "data": "NoHP" },
                        { "data": "Content" },
                        { "data": "Sender" },
                        { "data": "IsUsingTemplate" },
                        { "data": "Status" },
                        { "data": "CreatedDate" }
                    ],
                    columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                    order: [0, 'desc'],
                });
            }
        });
    });

    $(document).ready(function() {
        $.ajax({
            "url": "@Url.Action("GetAllFailedByUserToday", "Dashboard")",
            "type": "GET",
            "datatype": "json",
            "success": function(res) {
                const mapped = res.data.map((dt) => {
                    return {
                        ...dt,
                        CreatedDate: parseDate(dt.CreatedDate),
                        Status: dt.Status ? "Sukses" : "Gagal",
                        IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                    };
                });

                $("#getAllFailedToday").DataTable({
                    "data": mapped,
                    "dom": 'Bfrtip',
                    "buttons": ['copy', 'excel'],
                    "columns": [
                        { "data": "Nama" },
                        { "data": "NoHP" },
                        { "data": "Content" },
                        { "data": "Sender" },
                        { "data": "IsUsingTemplate" },
                        { "data": "Status" },
                        { "data": "CreatedDate" }
                    ],
                    columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                    order: [0, 'desc'],
                });
            }
        });


    });

</script>

我可以减少这些代码的重复吗?如果可以,请帮助我。所以我可以尝试申请另一个有同样问题的页面。谢谢。

【问题讨论】:

  • 您的问题非常广泛。从我在您的示例中可以看到,您可以将 DataTable(...) 回调的重复配置移动到一个对象中,然后将引用传递给函数。也可以在广告开头定义mapper function,然后直接用数据调用,这样就不用每次都重复了
  • 我投票结束这个问题,因为这个问题属于codereview.stackexchange.com
  • 将 ajax 等的轻微修改版本放入一个接受“action”和“tableID”参数的函数中,(我认为它们是唯一的)。然后调用该函数 3 次,每次都有自己的 action/tableID。在单个“jQuery(document).ready()”包装器中完成所有这些操作。
  • 对不起@VincentMenzel 我是 JS 新手。能给我举个例子吗?
  • @Roamer-1888 很好,我已经尝试过了,我只是调用了 URL 和 tableId。 ot 有效。谢谢:)

标签: javascript jquery asp.net asp.net-mvc


【解决方案1】:

更新,@Roamer-1888 的建议终于我尝试了,它有效!

function renderTable(action, tableId) {
    $.ajax({
        "url": action,
        "type": "GET",
        "datatype": "json",
        "success": function(res) {
            const mapped = res.data.map((dt) => {
                return {
                    ...dt,
                    CreatedDate: parseDate(dt.CreatedDate),
                    Status: dt.Status ? "Sukses" : "Gagal",
                    IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
                };
            });

            $(tableId).DataTable({
                "responsive": true,
                "lengthChange": false,
                "autoWidth": false,
                "data": mapped,
                "dom": 'Bfrtip',
                "buttons": ['copy', 'excel'],
                "columns": [
                    { "data": "Nama" },
                    { "data": "NoHP" },
                    { "data": "Content" },
                    { "data": "Sender" },
                    { "data": "IsUsingTemplate" },
                    { "data": "Status" },
                    { "data": "CreatedDate" }
                ],
                columnDefs: [{ 'targets': 0, type: 'date-euro' }],
                order: [0, 'desc'],
            });

        }
    });
}

$(document).ready(function() {
    renderTable("@Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
    renderTable("@Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
    renderTable("@Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多