Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Aspect-Oriented Programming Example. Live: http://jsfiddle.net/z8GXU/
<!DOCTYPE html>
<html lang="en">
<head>
<title>AOP Example</title>
<style type="text/css">
#log {
background: #EEE;
height: 300px;
overflow: auto;
}
</style>
</head>
<body>
<button id="callJohn">Call John</button>
<button id="callSteve">Call Steve</button>
<pre id="log"></pre>
<script src="http://requirejs.org/docs/release/2.1.14/comments/require.js"></script>
</body>
</html>
requirejs.config({
packages: [
{
name: "meld",
main: "meld",
location: 'https://rawgithub.com/cujojs/meld/master'
}
]
});
require(['meld'], function(meld) {
'use strict';
var john = { 'name': 'John', 'picksUp': true, 'message': 'Hey!' };
var steve = { 'name': 'Steve', 'picksUp': false };
// Phone class
function Phone() {};
Phone.prototype.dial = function (friend) {
if (friend && friend.picksUp) {
return friend.message;
} else {
throw 'No answer!';
}
};
// AOP
meld.before(Phone.prototype, 'dial', function () {
log(
'{}: Calling {}... ',
meld.joinpoint().method,
meld.joinpoint().args[0].name
);
});
meld.around(Phone.prototype, 'dial', function (joinPoint) {
var start = new Date().getTime();
var message = joinPoint.proceed();
var end = new Date().getTime();
log('Call lasted: {} milliseconds!', (end - start));
return joinPoint.args[0].name + ': ' + message;
});
meld.afterThrowing(Phone.prototype, 'dial', function (error) {
log('Error: {}', error);
});
meld.after(Phone.prototype, 'dial', function () {
// Append newline after dial no matter what
log('\n');
});
// Utility
function log() {
var message = arguments[0];
for (var i = 1; i < arguments.length; i++) {
message = message.replace('{}', arguments[i]);
}
$('#log').append(message + '\n');
}
function setup() {
var phone = new Phone();
$('#callJohn').click(function () {
phone.dial(john);
});
$('#callSteve').click(function () {
phone.dial(steve);
});
}
setup();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment