steveosoule
7/19/2013 - 10:01 PM

Decoupling Functions with Custom jQuery Events

Decoupling Functions with Custom jQuery Events

// Decoupling with Custom jQuery Events
// http://flippinawesome.org/2013/07/15/decoupling-with-custom-jquery-events/

/* ---- Do This: ---- */
var $doc = $(document);
$('.add-items').on('click', function(event) {
    doc.trigger('addItem', [$(this)]);
    event.preventDefault();
});

$doc.on('addItem', function(event, btnElement) {
    $('.something-else').addClass('foo')
});

$doc.on('addItem', function(event, btnElement) {
    $.ajax({
        // etc
    });
});


/* ---- Instead of This: ---- */
$('.add-items').on('click', function(event) {
    $('.loading-message').show();

    $.ajax({
        // etc
    });

    $('.something-else').addClass('foo')

    event.preventDefault();
});