Skip to content

Instantly share code, notes, and snippets.

@bcruddy
Last active September 12, 2016 19:29
Show Gist options
  • Save bcruddy/0a37528033c463ea28cc30196ba835b5 to your computer and use it in GitHub Desktop.
Save bcruddy/0a37528033c463ea28cc30196ba835b5 to your computer and use it in GitHub Desktop.
// here's an example of both higher order functions and currying.
// jquery's 'on' and 'each' are both higher order functions, as we pass functions as arguments.
// before we use the saveSubscriber function within the anonymous function passed into each, we curry it with the total # rows
// to establish an upper limit (so we know when we've processed the last row) - the returned function is saveRow
$(document).on('click', '#save-permissions', function() {
var $modifiedRows = $('#subscribers-bulk').find('tr.modified');
// here we curry saveSubscriber, passing in the the number of modified rows
var saveRow = saveSubscriber($modifiedRows.length);
$modifiedRows.each(function(index) {
saveRow(this, index);
});
});
function saveSubscribers(count) {
var errors = 0;
return function(row, index) {
var $row = null;
if (row instanceof $) $row = row;
else $row = $(row);
var $submitIcon = $('#manage-subscribers-content').find('#save-permissions > i');
var options = {
data: {
// some data to pass to the srver
},
success: function (res) {
var hasError = !res || res.error;
errors += hasError ? 1 : 0;
$row.removeClass('modified').toggleClass('danger', hasError).toggleClass('success', !hasError);
if (count - 1 === index) {
$submitIcon.removeClass('fa-pulse fa-spinner').addClass('fa-save');
if (errors > 0)
sweetAlert('Uh oh!', 'An error occurred updating a subscriber. The subscribers highlighted in red had errors.', 'error');
else
sweetAlert('Success!', 'All subscribers updated successfully.', 'success');
}
}
};
$submitIcon.removeClass('fa-save').addClass('fa-pulse fa-spinner');
helpers.call('/pro/savesubscriber', options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment