Class Events Demonstration

- binding handlers in a class - adding events to an element in a class - removing events from the element

HTML

<div id=nav>
    <a>Home</a>
    <a>About</a>
    <a>Contact</a>
</div>
<hr>
<button id=detach>detach</button> <button id=attach>attach</button>

CSS

body { margin-top: 10px;}

#nav a {
    padding: 8px 4px;
    cursor: pointer;
    font-family: helvetica, arial;
}

.current {
    background: #ff8;
}

hr {
    margin: 20px 0;
}

JavaScript

var Nav = new Class({

    Implements: [Options, Events],

    options: {
        currentClass: 'current'
    },

    initialize: function(element, options) {
        this.setOptions(options);
        this.element = document.id(element);
        this.current = null;
        this.bound = this.clickHandler.bind(this);
        
    },

   

    clickHandler: function(event) {
        this.setCurrent(event.target)
        return this;
    },

    setCurrent: function(target) {
        if (target == this.current) return;
        if (this.current) this.current.removeClass(this.options.currentClass);
        this.current = target.addClass(this.options.currentClass);
        this.fireEvent('click', target);
        return this;
    }

});

var nav = new Nav('nav').setCurrent($$('a:first-child'));