jQuery Custom Events Part 2

In part 1 we added custom events to a todo app. In this post we will be adding more complicated interactions.

Custom Events

`done.mark.todos.myapp`
    start marking a todo as done
`inprogress.mark.todos.myapp`
    marking a todo is currently in progress
`success.mark.todos.myapp`
    we are done marking the todo done on the server
`complete.mark.todos.myapp`
    happens after ajax returns with both success and error

By adding events during and after the ajax request to the server, we can provide interactions to give the user feedback during the process.

Once a user triggers the done event, we will remove the checkbox and add a spinner while a request is in progress. Then we can trigger a success event that checks the checkbox, removes the spinner and strikes the item.

Triggering states

$('.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,
        beforeSend: function(e) {
            this.trigger("inprogress.done.mark.todos.myapp")
        },
        success: function(resp) {
            this.trigger("success.done.mark.todos.myapp");
        },
        complete: function(resp) {
            // happens after success or error.
            this.trigger("complete.done.mark.todos.myapp")
        }
    });         
});

Listen for states

inprogress

$('.todo_list').delegate('li', 'inprogress.done.mark.todos.myapp', function(e) {
        var $checkbox = $(this).find(":checkbox");
        $checkbox.hide();
        $checkbox.before($("<img />", {
            src: "images/ajax-loader.gif",
            class: "loader"
        }));
});

success

$('.todo_list').delegate('li', 'success.done.mark.todos.myapp', function(e) {
    $(this).addClass("done");
    var $checkbox = $(this).find(":checkbox")
    $checkbox.attr('checked', true);
});

complete

$('.todo_list').delegate('li', 'complete.done.mark.todos.myapp', function(e) {
        var $checkbox = $(this).find(":checkbox");
        $checkbox.siblings('.loader').remove();
        $checkbox.show();
});

Try it out and see what you think.