JavaScript / jQuery on call函数事件

时间:2016-01-10 00:37:26

标签: javascript jquery

JavaScript / jQuery中是否有内置的调用函数事件?

我的意思是on('call' , function(){})

我同时使用这个自定义事件:

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

2 个答案:

答案 0 :(得分:1)

你应该使用jQuery' event对象:



function setCookie(name, value, days) {
    // set ...
    $.event.trigger({ type: "setCookieEvent", name: name, value: value });
}

function cookieController() {
  $(document).on("setCookieEvent", function(event) {
    document.write("Cookie " + event.name + " created with value " + event.value); 
  });
}


cookieController();

setCookie("cookie-name", "cookie-value", 100);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如上面的评论中所述,您可以使用一些新功能来装饰原始功能。您实际上是保存对原始函数的引用,并重写原始函数以包含一些新功能。

&#13;
&#13;
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 );
&#13;
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
&#13;
&#13;
&#13;