Created
September 27, 2012 18:25
-
-
Save gavacho/3795551 to your computer and use it in GitHub Desktop.
A shim for older versions of jQuery which don't have the `on` method defined.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function( $ ) { | |
'use strict'; | |
if ( !$.fn.on && $.fn.live && $.fn.bind ) { | |
$.fn.on = function() { | |
var args = createObjectFromArgs( arguments ); | |
if ( args.selector ) { | |
this.find( args.selector ).live( args.events, args.data, args.handler ); | |
} else { | |
this.bind( args.events, args.data, args.handler ); | |
} | |
// support chaining | |
return this; | |
}; | |
} | |
function createObjectFromArgs( args ) { | |
var o = {}, | |
argumentNames = getArrayOfArgumentNames( args ); | |
$.each( argumentNames, function( index, argumentName ) { | |
o[ argumentName ] = args[ index ]; | |
} ); | |
return o; | |
} | |
function getArrayOfArgumentNames( args ) { | |
if ( args.length === 2 ) { | |
return [ 'events', 'handler' ]; | |
} | |
if ( args.length === 3 && typeof args[ 1 ] === 'string' ) { | |
return [ 'events', 'selector', 'handler' ]; | |
} | |
if ( args.length === 3 && typeof args[ 1 ] !== 'string' ) { | |
return [ 'events', 'data', 'handler' ]; | |
} | |
if ( args.length === 4 ) { | |
return [ 'events', 'selector', 'data', 'handler' ]; | |
} | |
throw new Error( 'could not determine the order of arguments to jQuery.fn.on' ); | |
} | |
}( jQuery )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reinventing the wheel :(
https://github.com/MoonScript/jquery-on-off-shim/blob/master/jquery.on.off.js