views:

46

answers:

2

I need to be able to achieve the following (one way or another):

function ShowContent() {}

document.onShowContent = function ()
{
     // anything I want to happen....
}

What I'm trying to do is to add a kind of listener to me Advertisement code on the page that will auto refresh the ad slot when a specific function is called. Instead of having that function "ShowContent()" directly refresh the ad code, I want the ad code to refresh if it detects that "ShowContent()" has been called.

Thanks.

+4  A: 

Modern javascript libraries make this easy. You can do it "by hand" of course, but here's a quick example with jQuery

First, the listener

$(document).bind( 'ShowContent', function()
{
  // anything you want
});

Then the trigger

$(document).trigger( 'ShowContent' );

You could even go this route if you want

function ShowContent()
{
  $(document).trigger( 'ShowContent' );
}
Peter Bailey
Thanks Peter, the situation im faced with is that I cant change the trigger functions. I need something that will listen and detect the functions being triggered without having to be manually told that it was fired.
Laith
+1  A: 

Here is a quick sample i threw together

 var ev = (function(){
     var events = {};
     return {
         on: function(name, handler){
             var listeners = (name in events) ? events[name] : (events[name] = []);
             listeners.push(handler);
         },
         raise: function(name){
             var listeners = events[name];
             if (listeners) {
                 var i = listeners.length;
                 while (i--) {
                     listeners[i]();
                 }
             }
         }
     };
 })();

 // add a listener
 ev.on("foo", function(){
     alert("bar");
 });

If you cannot manually alter the method in question to trigger the event, then you can 'wrap' it.

 function methodIHaveNoControlOver(){
     ....
 }

 // intercept the call
 var originalFn = methodIHaveNoControlOver;
 // here we replace the FunctionDeclaration with a FunctionExpression containing a reference to the original FunctionDeclaration
 methodIHaveNoControlOver = function(){
     originalFn();
     ev.raise("foo");
 };

But note that this will not work if methodIHaveNoControlOver uses this to reference anything; so that will require more work.

Sean Kinsey
Thanks Sean,My comment on Peter's suggestions also applies here. I want to be able to just call foo() and have listener function/code detect that without he having to explicitly tell it.
Laith
I added code to show you how to work around this.
Sean Kinsey