Skip to content

Instantly share code, notes, and snippets.

@drublic
Last active December 12, 2015 06:08
Show Gist options
  • Save drublic/3457c27e8681a34b75d9 to your computer and use it in GitHub Desktop.
Save drublic/3457c27e8681a34b75d9 to your computer and use it in GitHub Desktop.
(function ($) {
if ($.fn.on === undefined) {
$.fn.on = function (types, selector, data, fn) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
$.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data === null && fn === null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn === null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
return this.each( function( types, selector, data, fn ) {
jQuery.event.add( this, types, fn, data, selector );
});
};
}
if ($.fn.off === undefined) {
$.fn.off = function () {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
};
}
}(jQuery));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery.fn.on polyfill</title>
</head>
<body>
<div class="message"></div>
<a href="#" class="off">Remove Events</a>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="jquery.eventspolyfill.js"></script>
<script>
$( document ).on( 'click', function () {
$( '.message' ).text( 'clicked ' + ( +new Date() ) )
});
$( '.off' ).on( 'click', function () {
$( document ).off( 'click' );
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment