Skip to main content

AOP in JavaScript with jQuery

April 03, 2012 mgroves 0 Comments
Tags: JavaScript jQuery jQuery aop

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":

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.


Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments