简体   繁体   English

Javascript应用程序:糟糕的设计使数百个Ajax调用

[英]Javascript application: bad design makes hundreds of ajax calls

I've made a question on the forum about a issue I was facing in my application. 我做了一个问题,关于我正面临着我的应用程序中的问题的论坛。 Although the question was marked as duplicate, I tried to use the good practices to solve the problem. 尽管该问题被标记为重复,但我还是尝试使用良好实践来解决问题。 After very tries my code finnaly works, but not in the way I expected. 经过非常尝试,我的代码终于可以正常工作了,但是并没有达到我的预期。 I'm making an application using the Fullcalendar plugin. 我正在使用Fullcalendar插件制作应用程序。 In the "eventRender" callback, which is executed to each event on the calendar, the callback I've made is making hundreds of ajax calls :@ I think I don't understand very well all that callback thing. 在对日历上每个事件执行的“ eventRender”回调中,我进行的回调正在进行数百个ajax调用:@我想我对所有这些回调事情不太了解。 Here's my code: 这是我的代码:

    $().ready(function() {
        var obterDadosCategorias = (function() {
            var dadosCategorias;

            var efetuarPost = function(callback){
                $.post(
                    "{{ baseRoute }}/cadastro/categoria/listar"
                    , {
                        "ajax": "true"
                    }
                ).done(function(data) {
                    var obj = $.parseJSON(data);
                    if (obj.result) {
                        callback(obj.data);
                    } else {
                        alert('Erro interno: não foi possível obter os dados das categorias');
                    }
                }).fail(function(){
                    alert('Erro interno: não foi possível obter os dados das categorias');
                });
            };

            return function(callback) {
                if (dadosCategorias) {
                    callback(dadosCategorias);
                    return;
                }

                efetuarPost(function(dados) {
                    dadosCategorias = dados;
                    callback(dados);
                });
            };
        })();

        $("#fullcalendar").fullCalendar({
            "eventRender": function(event, element, view) {
                if (view.name === "month") {
                    var beforeMonth = parseInt(event.end.format("YYYYMMDD")) < parseInt(view.intervalStart.format("YYYYMMDD"));
                    var afterMonth = parseInt(event.start.format("YYYYMMDD")) > parseInt(view.intervalEnd.clone().subtract(1, 'days').format("YYYYMMDD"));

                    if (beforeMonth || afterMonth) {
                        return false;
                    }
                }

                obterDadosCategorias(function(dadosCategorias) {
                    $(element).css("background-color", dadosCategorias["id_" + event.categoria].cor).css("color", textoBrancoOuPreto(dadosCategorias["id_" + event.categoria].cor));
                });

                return $(element);
            }
        });
    });

Hope you guys can help me. 希望你们能帮助我。 :D Thanks in advance. :D在此先感谢。

Using asynchronous code requires you to think differently about how your functions should be structured. 使用异步代码要求您对函数的结构应有不同的思考。 Instead of thinking: "I need to write a function that returns a value," you should be thinking "I need to write a function that performs an action once I have a value." 与其思考:“我需要编写一个返回值的函数”,而是应该思考“我需要编写一个一旦有值就执行操作的函数”。

It appears your only need for an AJAX call is to get your list of categories. 看来,您唯一需要进行AJAX调用的就是获取类别列表。 You are currently making that AJAX request every time an event is rendered on your calendar. 当前,每次在日历上呈现事件时,您都在发出AJAX请求。 Instead you should get the categories once, then initialize your calendar after retrieving them. 相反,您应该一次获得类别,然后在检索它们之后初始化日历。

The other key is storing the categories where they can be accessed in your renderEvent handler. 另一个键是存储类别,可以在您的renderEvent处理程序中访问它们。 I solved this below by using JavaScript Closures , but you could also use a global variable (preferably namespaced). 我在下面通过使用JavaScript Closures解决了这个问题,但是您也可以使用全局变量(最好是命名空间)。

I believe this code accomplishes all you are looking for: 我相信这段代码可以满足您的所有需求:

$(document).ready(function() {  

    $.post(
        "{{ baseRoute }}/cadastro/categoria/listar"
        , {
            "ajax": "true"
        }
    ).done(function(data) {
        $("#fullcalendar").fullCalendar({
            "eventRender": createRenderEvent($.parseJSON(data))
        });

    }).fail(function(){
        alert('Erro interno: não foi possível obter os dados das categorias');
    });

    function createRenderEvent(dadosCategorias) {
        return function(event, element, view) {
            if (view.name === "month") {
                var beforeMonth = parseInt(event.end.format("YYYYMMDD")) < parseInt(view.intervalStart.format("YYYYMMDD"));
                var afterMonth = parseInt(event.start.format("YYYYMMDD")) > parseInt(view.intervalEnd.clone().subtract(1, 'days').format("YYYYMMDD"));

                if (beforeMonth || afterMonth) {
                    return false;
                }
            }

            $(element).css("background-color", dadosCategorias["id_" + event.categoria].cor).css("color", textoBrancoOuPreto(dadosCategorias["id_" + event.categoria].cor));
            return $(element);
        }
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM