YUI CustomEvent subscriptions

Recently at Ajaxian there was a post describing Custom Events and how they could be used to better structure an event-driven application by ’subscribing’ or ‘binding’ certain actions to an event. At Pint we use YUI as our main library, so I’ve ported the author’s example into a version that uses YUI.

Here is the code:

YAHOO.util.Event.onDOMReady(function() {
    document.body.event1 = new YAHOO.util.CustomEvent();
    YAHOO.util.Event.on('colorchange', 'change', function(e) {
        if (this.checked) document.body.event1.subscribe(changeColor);
        else document.body.event1.unsubscribe(changeColor);
    });
    YAHOO.util.Event.on('contentchange', 'change', function(e) {
        if (this.checked) document.body.event1.subscribe(changeContent);
        else document.body.event1.unsubscribe(changeContent);
        }
    });
    YAHOO.util.Event.on(document.getElementById('leftchoices').childNodes, 'click', function(e) {
        document.body.event1.fire(e);
    });
});

See example »

Tags: , ,

Leave a Reply