Skip to content

Instantly share code, notes, and snippets.

@cowboy
Forked from remy/gist:378764
Created April 26, 2010 12:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/379255 to your computer and use it in GitHub Desktop.
Save cowboy/379255 to your computer and use it in GitHub Desktop.
Just another way of doing it...
// "Cheat" special event using this pattern:
// http://benalman.com/news/2010/03/jquery-special-events/#pattern
//
// Also see:
// http://benalman.com/news/2010/03/jquery-special-events/#add-and-remove-tripleclick-per-handler
(function($){
$.event.special.cheat = {
setup: function() {
$(this).bind( 'keydown', handler );
},
teardown: function() {
$(this).unbind( 'keydown', handler );
},
add: function( handleObj ) {
var old_handler = handleObj.handler,
code = handleObj.data,
keys = [];
if ( /[a-z]/i.test(code) ) {
code = $.map( code.toUpperCase().split(''), function(letter){
return letter.charCodeAt(0);
}).join(' ');
}
handleObj.handler = function( event, which ){
keys.push(which);
if ( keys.join(' ').indexOf(code) >= 0 ) {
keys = [];
old_handler.apply( this, arguments );
}
};
},
};
function handler( event ) {
$(this).triggerHandler( 'cheat', [ event.which ] );
};
})(jQuery);
// Konami-code-specific "cheat" implementation.
(function($){
var konami = '38 38 40 40 37 39 37 39 66 65';
$.event.special.konami = {
setup: function () {
$(this).bind( 'cheat', konami, handler );
},
teardown: function () {
$(this).unbind( 'cheat', handler );
}
};
function handler( event ) {
$(this).triggerHandler( 'konami', event.which );
};
})(jQuery);
// Usage examples.
$('body').bind( 'cheat', 'foo', function(e){
console.log( e.type, this, 'foo!' );
});
$('body').bind( 'konami', function(e){
console.log( e.type, this, 'konami!' );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment