代码改变世界

javascript delegate函数

2010-08-23 23:45  BlueDream  阅读(1703)  评论(1)    收藏  举报

// Usage:
// Target all links with an ID starting with "notice"
delegateEvent({nodeName:/^a$/i, id: /^notice/}, 'click', function(){
    alert(this.id);
});


function delegateEvent(props, type, handler) {
    
    var fn = function(e) {
        
            e = e || window.event;
            
            var target = e.target || e.srcElement,
                parent = target,
                p, prop, matches = false;
            
            do {
                
                matches = false;
                
                for (p in props) {
                    if (!props.hasOwnProperty || props.hasOwnProperty(p)) {
                        prop = props[p];
                        matches = prop.test ? prop.test(parent[p]) : prop === parent[p];
                    }
                }
                
                if (matches) {
                    return handler.call( parent, e );
                }
                
            } while ( parent = parent.parentNode );
            
            return true;
        
        },
        doc = document;
    
    if (doc.addEventListener) {
        
        doc.addEventListener( type, fn, false );
        
    } else {
        
        if (doc.attachEvent) {
            doc.attachEvent( 'on' + type, fn );
        } else {
            var origHandler = doc['on' + type];
            doc['on' + type] = function(e) {
                origHandler.call(this, e);
                fn(e);
            };
        }
        
    }
    
}