Created
April 25, 2010 22:04
-
-
Save remy/378764 to your computer and use it in GitHub Desktop.
konami as a special event
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
/** | |
* 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); |
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
Remy, you should consider using my special event plugin pattern:
http://benalman.com/news/2010/03/jquery-special-events/#pattern