jQuery Custom Events

Let's say you are building a todo app. All is well and good in the world until you want to start expanding your app. Without custom events, every time you add interactions you have to constantly change your code. When a user clicks on the checkbox or on the mark all link we can trigger a mark as complete event. We can then trigger the same event using yet unknown interactions like keyboard shortcuts or iphone swipe motions without having to change our underlying code. We can actually trigger any event we want.

$(el).trigger("the.apocolypse");

Pretty scary huh. Had this been real working code instead of an example, you wouldn't need to read any further as the world would have asploded. And remember, With great power comes great responsibility...

You can have any number of listeners. For example, you could enable logging if an administrator is logged in. All you would have to do is listen for an event in your logging code and you wouldn't have to change any production code!

Adding custom events to our todo app

Our new made-up event will be done.mark.todos.myapp. The dots create namespaced events. Before we get started, you may want to see it in action .

Triggering done when the checkbox is clicked

$('.todo_list').delegate(':checkbox', 'click', function(e) {
    $(this).closest('li').trigger("done.mark.todos.myapp");
});

Triggering done when the mark all link is clicked

$('a.mark_all').click(function(e) {
    e.preventDefault();
    $(this).siblings('li').each(function(i, el) {
        $(el).trigger('done.mark.todos.myapp');
    });
});

Listening for done

$('.todo_list').delegate('li', 'done.mark.todos.myapp', function(e) {
//send todo item to server for marking...
    var $this = $(this);
    $.ajax({
        url: "",
        method: 'POST',
        context: $this,
        success: function(resp) {
            this.addClass("done")
                .find(":checkbox")
                    .attr('checked', true);
        }
    });     
});

This replaces our original click handlers with custom events, but doesn't change any of the original functionality. To see how to improve even further, see part 2.