Multiple ajax when creating a jquery module

0

I have created a module / plugin in jquery. This creates a select and inserts the options taking the information by ajax.

The problem is that when creating 2 selects he makes me 2 ajax calls.

(function ($) {
var property = {
    calendars: {},
    calendarAjax: $()
}
$.fn.scheduler = function (options) {
    var $element = $();
    var method = {
        getCalendars: function () {
            if (Object.keys(property.calendars).length < 1) {
                if (typeof property.calendarAjax.done === 'undefined') {
                    property.calendarAjax = $.ajax({
                        type: 'POST',
                        url: '/cals/CalendarList',
                        dataType: 'JSON'
                    }).then(function (r) {
                        var lendars = {};
                        $.each(r['calendars'], function (k, v) {
                            if (typeof v !== 'undefined') {
                                lendars[v['id']] = v;
                            }
                        });
                        property.listCalendars = lendars;
                    }, 'JSON');
                }
            }
            if (property.calendarAjax.done()) {
                property.calendarAjax = $.Deferred();
            }
        }
    }

    $element = $(this);
    return {
        selectPickerCalendar: function () {
            method.getCalendars();
            property.calendarAjax.then(function () {
                $element.selectCalendars({
                  listCalendars: property.listCalendars
                });

            });

        }
    }
}})(jQuery);

And if I call it twice in the way:

$('#selec1').scheduler().selectPickerCalendar();
$('#selec2').scheduler().selectPickerCalendar();

then he makes me 2 calls to the server because in the second he has not had time to get a response yet and he makes the call again.

So, I was thinking about !ifAjaxIsCompleted() and pass some connection identifier or a deferred that is global but as you can see, that's what I tried.

Any ideas?

Thank you very much

    
asked by Txmx 02.08.2018 в 12:55
source

1 answer

0

You can modify your plug-in to work with multiple selectors, such as:

$('#selec1, #selec2').scheduler().selectPickerCalendar();

I find the behavior "normal" for jQuery.

    
answered by 02.08.2018 в 13:32