Binary Lion Studios

I code for fun and for food.

Binding events to functions

jQuery is DOM-centric. I wanted to play around with binding events to functions. There are two reasonable ways I can think of doing it.

Option 1 - Use local dispatcher
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
(function($) {

    $(document).ready(function() {
        updateList().bind('updateListComplete', function(e, data) {
            $("#list").html(data);
        });
    });

    function updateList() {
        /** Use local event dispatcher. */
        var dispatcher = $({});
        $.ajax({
            type: 'GET',
            url: 'http://example.com/things',
            success: function(data) {
                dispatcher.trigger('updateListComplete', [data]);
            }
        });
        return dispatcher;
    }

    function addSomethingToList(thingToAdd) {
        $.ajax({
            type: 'POST',
            url: 'http://example.com/things',
            data: thingToAdd,
            success: function(data) {
                updateList().one('updateListComplete', function() {
                    showMsg('Your something was added. Yay.');
                });
            }
        });
    }

})(jQuery);
Option 2 - Use global event bus
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(function($) {

    /** Use global event bus. */
    var events = $({});

    $(document).ready(function() {
        events.bind('updateListComplete', function(e, data) {
            $("#list").html(data);
        });
        updateList();
    });

    function updateList() {
        $.ajax({
            type: 'GET',
            url: 'http://example.com/things',
            success: function(data) {
                events.trigger('updateListComplete', [data]);
            }
        });
    }

    function addSomethingToList(thingToAdd) {
        $.ajax({
            type: 'POST',
            url: 'http://example.com/things',
            data: thingToAdd,
            success: function(data) {
                events.one('updateListComplete', function() {
                    showMsg('Your something was added. Yay.');
                });
                updateList();
            }
        });
    }

})(jQuery);

I like Option 1 because it feels more jQueryish (with the chaining). However, I think Option 2 is cleaner and easier to understand.