Ad

JavaScript / JQuery On Call Function Event

- 1 answer

Is there built-in on call function event in JavaScript / jQuery ?

I mean something on('call' , function(){})

I use this custom event meanwhile:

function setCookie(name, value, days) {
    // set ...
    $(document).trigger( "setCookieEvent", [ name ] );
}
function cookieController()
{
    $(document).on( "setCookieEvent", function( event, name ) {
        //setCookie name
    });
}
cookieController();
Ad

Answer

As said in the comments above, you could decorate the original function with some new functionality. You are essentially saving a reference to the original function, and rewriting the original function to include some new functionality.

function setCookie( name, value, days ) {
  console.log('setCookieCalled ' + name, value, days );
}

setCookie('[before decoration]', 'foo', 1 );

// rewrite the setCookie function
setCookie = decorate(setCookie, function( name, value, days ){
  console.log('decorated setCookie ' + name, value, days );
});

// this will modify the original function. and return a new function that decorates the old.
function decorate(originalFunction, decorator) {
  return function( /* arguments */ ) {
    console.log('called decorator ' + arguments[0] );
    // call the decorator and the original function
    decorator.apply( this, arguments );
    originalFunction.apply( this, arguments );
  }
}

setCookie('[after decoration]', 'bar', 2 );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

Ad
source: stackoverflow.com
Ad