Skip to content

Instantly share code, notes, and snippets.

@chicagoworks
Created December 24, 2010 18:48
Show Gist options
  • Save chicagoworks/754445 to your computer and use it in GitHub Desktop.
Save chicagoworks/754445 to your computer and use it in GitHub Desktop.
Override jquery.delegate() to accept an object
/**
* Override .delegate()
* if 'selector' is an object loop over the object and call .live() for each item
* otherwise it call .live() just like the original .delegate().
* Roughly similar to the way the map is implemented in .bind().
*/
$.fn.delegate = function(selector, types, data, fn) {
if (typeof selector === "object") {
for (var sel in selector) {
for (var type in selector[sel]) {
this.live(type, data, selector[sel][type], sel);
}
}
return this;
} else {
return this.live(types, data, fn, selector);
}
};
@chicagoworks
Copy link
Author

Usage

Call delegate with an object map of selectors, events and function

$('#header').delegate({
    'img' : {
        'click dblclick':function() {
            console.log('clicked')
        }
    },
    'li' : {
        mouseover:function() {
            console.log('over')
        },
        mouseout:function() {
            console.log('out')
        }
    }
}, {foo:123 , bar:456});

//test regular delegate call
$('#header').delegate('img', 'click dblclick', function click() {
    console.log('clicked')
});

//test regular delegate call with a data object
$('#header').delegate('img', 'click dblclick', {foo:123 , bar:456}, function click() {
    console.log('clicked')
});

@adam-lynch
Copy link

I assume .delegate now calls .on() underneath?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment