Created
September 4, 2015 05:06
-
-
Save jmichelsen/795bd2078eb33540396c to your computer and use it in GitHub Desktop.
An Example of Promises in JavaScript (JQuery)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $(document).on('click', '.mass-add-fields', function() { | |
| $("td.active").find('.toggle').click(); | |
| var checkedOfferFormIds = []; | |
| function checkedOffersWithoutForms() { | |
| var $checkedOffers = $('.offer.checked').find('button[data-create="true"]'), | |
| $promises = [], | |
| d = $.Deferred(); | |
| if ( !$checkedOffers.length ) { | |
| return d.resolve('no forms needed creating').promise(); | |
| } else { | |
| $checkedOffers.each(function() { | |
| var $button = $(this), | |
| offerId = $button.closest('tr').data('offer-id'); | |
| $promises.push( | |
| $.get('/contracts/offer_form/create/offer/' + offerId + '/').done(function(response) { | |
| var formId = $(response).find('.form-id').val(); | |
| $button.data('form-id', formId); | |
| $button.attr('data-create', 'false'); | |
| checkedOfferFormIds.push($button.data('form-id')); | |
| $button.find('.offer-field-count').text('0'); | |
| }) | |
| ); | |
| }); | |
| $.when.apply($, $promises).then(function() { | |
| d.resolve(); | |
| }); | |
| return d.promise(); | |
| } | |
| } | |
| function checkedOffersWithForms() { | |
| var d = $.Deferred(); | |
| var $checkedOffers = $('.offer.checked').find('button[data-create="false"]'); | |
| $checkedOffers.each(function() { | |
| checkedOfferFormIds.push($(this).data('form-id')); | |
| }); | |
| d.resolve(); | |
| return d.promise(); | |
| } | |
| $.when(checkedOffersWithForms(), checkedOffersWithoutForms()).then(function() { | |
| if ( !checkedOfferFormIds.length ) { | |
| alert('No offers checked for mass update'); | |
| return; | |
| } | |
| var data = { | |
| form_id: checkedOfferFormIds | |
| }; | |
| $.get('/contracts/offer_form/mass-add/', data, function(response) { | |
| var $modalXl = $('#generic-modal-xl'); | |
| $modalXl.find('.modal-content').html(response).end().modal('show'); | |
| }) | |
| }).fail(function() { | |
| console.log('"When" failed. Look to the code, Luke.'); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment