Created
July 10, 2014 11:29
-
-
Save auramo/7ebc10d971802106d15a to your computer and use it in GitHub Desktop.
Javascript JQuery Deferred promise ajax stuff
This file contains 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
function bindBarCodeValidation() { | |
$('#shoppingcart').debounced('input keyup', 'input[name="barcode"]', onSchedule, onFire, 500, rowIdentity); | |
function onSchedule() { | |
$(this).addClass('input-loader'); | |
return true; | |
} | |
function onFire() { validateBarcode($(this)); } | |
function rowIdentity() { return $(this).closest('[data-row-id]').attr('data-row-id'); } | |
function validateBarcode($target) { | |
var barcodeInput = $target.val(); | |
if (_.isEmpty(barcodeInput.trim())) { | |
onSuccess($target)(); | |
return; | |
} | |
ajaxGet('barcodes/' + barcodeInput).then(uniqueBarcodeInCart($target)).done(onSuccess($target)).fail(onError($target)); | |
} | |
function uniqueBarcodeInCart($target) { | |
return function() { | |
var deferred = new $.Deferred(); | |
var barcode = $target.val(); | |
if (isUnique(barcode)) deferred.resolve(); | |
else deferred.reject(); | |
return deferred; | |
}; | |
function isUnique(barcode) { | |
var nonEmptyBarcodesInCheckout = _($('#shoppingcart'). | |
find('input[name="barcode"]')). | |
map(function(elem) { return $(elem).val(); }). | |
filter(function(val) { return !_.isEmpty(val.trim()); }). | |
value(); | |
return _(nonEmptyBarcodesInCheckout). | |
filter(function(val) { return barcode.trim() === val.trim(); }). | |
value().length === 1; | |
} | |
} | |
function onSuccess($target) { | |
return function() { | |
$target.removeClass('input-loader error'); | |
toggleSubmitEnablation(); | |
} | |
} | |
function onError($target) { | |
return function() { | |
$target.removeClass('input-loader'); $target.addClass('error'); | |
toggleSubmitEnablation(); | |
} | |
} | |
} | |
function ajaxGet(suffix) { | |
return $.ajax({ | |
url: "/yrityksille/mint/apiversion/1/" + suffix, | |
contentType: 'application/json', | |
type: 'GET'}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment