Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

konami as a special event

View gist:378764
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/**
* konami cheat code as a jQuery special event - *not* a demo of how small
* I could take the code, since this is tons smaller:
* http://www.newmediacampaigns.com/page/konami-code-jquery-plugin-pointlessly-easy
* !!! :-)
*
* I should add, I'm almost certain someone else has done this already!
*/
(function ($) {
 
var konami = '38 38 40 40 37 39 37 39 66 65';
 
$.event.special.cheat = {
setup: function (data, namespace) {
$(this).bind("keydown", $.event.special.cheat.handler);
},
teardown: function (namespace) {
$(this).unbind("keydown", $.event.special.cheat.handler);
},
add: function(details) {
// get the required number of clicks from data
var handler = details.handler,
data = details.data,
code = data.code || konami,
keys = [];
 
if (/[a-z]/i.test(code)) {
code = $.map(code.toUpperCase().split(''), function (letter) {
return letter.charCodeAt(0);
}).join(' ');
}
 
// return a new function that will become the handler
details.handler = function(event) {
keys.push(event.which);
if (keys.join(' ').indexOf(code) >= 0) {
keys = [];
event.type = 'cheat';
handler.apply(this, arguments);
}
};
},
handler: function (event) {
event.type = 'cheat';
$.event.handle.apply( this, arguments );
}
};
 
$.event.special.konami = {
setup: function (data, namespace, handler) {
$(this).bind("cheat", { code: konami }, $.event.special.konami.handler);
},
teardown: function (namespace) {
$(this).unbind("cheat", $.event.special.konami.handler);
},
handler: function (event) {
event.type = 'konami';
$.event.handle.apply(this, arguments);
}
};
 
})(jQuery);

Remy, you should consider using my special event plugin pattern:
http://benalman.com/news/2010/03/jquery-special-events/#pattern

  • Ben
Owner
remy commented

Having read through a few times, I'm not convinced there's any benefit to using that pattern over what I've got already. In fact there's an additional function call over using $.event.special.konami.handler twice.

What's the advantage if I've missed it?

So I forked this. Advantages to my way:

  • minifies smaller
  • arguably more readable code (triggerHandler feels more clear than $.event.handle.apply)
  • no need to specify the event.type
  • one less (unnecessary) public method ($.event.special.foo.handler)

And as an aside, i changed the way the cheat-code-as-data is passed, as a string instead of as an object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.