Simple JavaScript Hooks

I recently had cause to inject some business logic into a JavaScript framework. I’m trying to keep the framework as generic as possible so I want to keep from hard-coding the business logic directly into the framework. In a C# context we might simply override the desired method to insert our behavior. You can override a function, in a way, in JavaScript. However, in my opinion, it’s not as clean.

After doing a bit of research, I found the following approach using jQuery. So far it works well. You define your ‘hook’ by simply doing the following:

 $(document).bind('OnSave', function() {
    //Insert code/logic here.

To execute the hook, you simply do this:


The beauty of this approach is that if you don’t bind a hook called ‘OnSave’, nothing happens. You are free to bind a function to the hook or not. It’s your choice.

You can also pass parameters into the hook like this:

 $(document).trigger('OnSave', [description, value]);

Where ‘description’ and ‘value’ are arbitrary variables that you want to pass to the hook. When using these hooks, the bind method call looks like this:

 $(document).bind('OnSave', function (description, value) {
     //Insert code/logic here.

That’s it! You can find the jQuery documentation for here and here.

Happy Coding!

Share this Story:
  • facebook
  • twitter
  • gplus

About Jeremy Foltz

Leave a comment