jQuery Events

How to prevent spaghetti code

by MoonScript

HTML

<div id="widget-a" class="widget">
    <p>Widget A</p>
    <p><a href="#" data-widget="a">Do &quot;Widget A&quot; stuff</a></p>
</div>
<div id="widget-b" class="widget">
    <p>Widget B</p>
    <p><a href="#" data-widget="b">Do &quot;Widget B&quot; stuff</a></p>
</div>
<div id="widget-c" class="widget">
    <p>Widget C</p>
    <p><a href="#" data-widget="c">Do &quot;Widget C&quot; stuff</a></p>
</div>

CSS

.widget {width: 200px; height: 50px; border: 1px solid #000; -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; padding: 8px; margin: 16px;}

JavaScript

var WIDGET = {
    a: function() {
        console.log('Widget A');
        $(this).trigger('widget', ['A']);
        //$(document).trigger('widget-a');
        return false;
    },
    b: function() {
        console.log('Widget B');
        $(this).trigger('widget', ['B']);
        //$(document).trigger('widget-b');
        return false;
    },
    c: function() {
        console.log('Widget C');
        $(this).trigger('widget', ['C']);
        //$(document).trigger('widget-c');
        return false;
    }
};
    
// Triggered by all widgets on the link, but bubbled up to the document
$(document).bind('widget', function(e, widgetLetter){
    console.log(e);
    $(e.target).css({
        color: '#FFF',
        backgroundColor: 'blue'
    })
    if (widgetLetter === 'B') {
       $(WIDGET).trigger('foo');
    }
});

// Bound to an object (not in the DOM)
$(WIDGET).bind('foo', function(){
    alert('WIDGET "foo" event triggered!');
});

// Don't worry about this; just setup to bind the click to each link
$('a').click(function(){
    var widgetLetter = $(this).attr('data-widget');
    return WIDGET[widgetLetter].call(this);
});