簡體   English   中英

JavaScript / jQuery on call函數事件

[英]JavaScript / jQuery on call function event

在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();

你應該使用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> 

如上面的評論中所述,您可以使用一些新功能來裝飾原始函數。 您實際上是保存對原始函數的引用,並重寫原始函數以包含一些新功能。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM