My code seems flawed, I’m setting two functions with the same code inside. Can I combine them into one?
// remove sets
$('body').on("click", "span.remove", function() {
var self = $(this),
total = self.parents('ul').children('li').size(); // grab total number of li's
// remove (set) li if total greater than 1, else remove exercise
if(total > 1)
self.parent('li').fadeOut('slow', function() {
// remove clicked .li and reset list order
$(this).remove();
reset();
});
else
self.parents('section').fadeTo('slow', 0.33).slideUp('slow', function() {
// remove clicked .li and reset list order
$(this).remove();
reset();
});
});
Is it possible to do something like:
if(total > 1)
var f = self.parent('li').fadeOut('slow', function()
else
var f = self.parents('section').fadeTo('slow', 0.33).slideUp('slow', function()
f {
// remove clicked .li and rest list order
$(this).remove();
reset();
});
The trick is to create a named function, instead of an anonymous function. A named function can then be passed around by reference, including as a parameter to other methods. There are two ways to do this, either as an expression (
function someName(){..}) or an assignment (var someName = function() {..}). Which you choose is mainly personal preference, they are effectively the same.An example (using a function expression), following on from your question below: