Posts tagged with 'jQuery'
There was a period of time that I was really into the game show Jeopardy!
I even had aspirations of becoming a contestant on the show, but alas it hasn't happened yet. But I did some research, and tried to figure out the best way to study/practice.
One of the best ways to practice is to actually play along with episodes of the show. Karl Coryat, a contestant on the show in 1996, came up with a way that you can practice at home and track how well you are doing. I started doing this, but it was somewhat tedious to do it with pen/paper or even an Excel sheet, so I wrote a little HTML/JavaScript to do most of the tedious stuff for me.
You can check out my Coryat Scorekeeper now on Github. It's actually a pretty old piece of code at this point (it uses jQuery 1.4.0, which I believe was the latest release at the time I wrote it). It could probably use a fresh coat of paint (and an updated reference for the average Coryat score), but it's still functional!
In a previous post, I showed off prototype's 'wrap' function, which gives JavaScript some AOP capabilities.
jQuery, a tool that I'm more familiar with, doesn't have an equivalent function that I know of. But there is a jQuery AOP plugin that provides a great AOP framework to your JavaScript.
While 'wrap' is akin to 'interception' style AOP, jQuery-aop includes some 'boundary' style aspects (as well as replacement/interception), including:
- before a method
- after a method
- when a method throws an exception
- when a method completes (exception or not)
- "around" a method
- replace a method (i.e. an "introduction")
There is some good API documentation available. Here's a little 101 example using "before" and "after":
<html> | |
<head> | |
<title>AOP with jQuery 1</title> | |
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script> | |
<script type="text/javascript" src="aop.min.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function() { | |
$.aop.before( {target: window, method: 'DisplayUserAgent'}, | |
function(args) { | |
alert("About to execute DisplayUserAgent on element with id '" + args[0] + "'"); | |
} | |
); | |
$.aop.after( {target: window, method: 'DisplayUserAgent'}, | |
function(returnVal) { | |
alert("Done executing DisplayUserAgent. It returned: '" + returnVal + "'"); | |
} | |
); | |
DisplayUserAgent("txtExample"); | |
}); | |
function DisplayUserAgent(elementId) | |
{ | |
$("#" + elementId).text(navigator.userAgent); | |
return navigator.userAgent | |
} | |
</script> | |
</head> | |
<body> | |
<p id="txtExample">This text will be updated with your user agent info</p> | |
</body> | |
</html> |
Just paste that into an HTML file and run it in your browser, and you should get two alert messages. Since it's JavaScript, you can apply AOP to built-in functions like String.replace, or jQuery functions, just as easily as you can functions that you've written.