-
-
Save cowboy/379255 to your computer and use it in GitHub Desktop.
Just another way of doing it...
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
// "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