简体   繁体   中英

How to automatically handle javascript function call and wrap/decorate it

Hello I have problem with existing javascript code.

The background is that some of JSP Tags automatically include JS function, and then some of html elements need to run this functions. But the point is that there a lot of html elements that need to use included JS function, and there will be very hard to modify each separate element to configure which function it should run.

Lets consider simple example: we have JSP Tag that generate table

<table id="automaticallyGeretatedId">
<tr>
<td></td>
</tr>
</table>

and this include some JS function

function removeItemFromTable(){
    //modify automaticallyGeretatedId
}
function addItemToTable(){
    //modify table, add values and so on..
}

then we have some html external buttons or/and div-s that have method with constant name "clearData" but the JS is a part of HTML page sometimes in this way (embedded in Html)

<script>
function clearData(){/*some code*/}
</script>

and sometimes in included file as

function clearData(){ //some code
}

So my question is: is other way than modify each simple clearData in code, to ensure that each time when clearData function will be run, the function removeItemFromTable() will be also run?

I mean can I search for clearData function and append after it call to removeItemFromTable function? And where should be this operation done, what is the best way to do this?

Lets suppose that each time when clearData() function appear the function removeItemFromTable() also will be included.

Finally I decided to use described at this link technique:

Adding code to a javascript function programmatically

I set up at document ready to search function clearData()

$( document ).ready(function() {
    decorateClearData();
});

and code in function decorateClearData();

function decorateClearData() {
    clearData = (function() {
    var cached_function = someFunction;

    return function() {
        cached_function.apply(this, arguments); // use .apply() to call it

        // and my new code:
        removeItemFromTable();
    };
}());
}

This works because clearData is global function, and maybe this is not pragmatic way but I didn't have other ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM