Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you re-use javascript functions

Tags:

javascript

We have lots of javascript functions, which are usually handled via the onclick function. Currently they are present in every file where-ever it is needed. Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed? What is the general practice here

            <s:link view="/User.xhtml"
                onclick="if (confirm('#{messages['label.user.warning']}')) {
                    var f = $('user');
                    f.method = 'POST';
                    f.action = f.submit();
                    } return false;">
like image 214
user339108 Avatar asked Dec 12 '22 19:12

user339108


2 Answers

Yes! Absolutely factor this out into an external javascript. Imagine if you needed to change something in this code. How many places do you have to change now? Don't duplicate code. It must makes your page bigger, which obviously affects how much is getting downloaded.

like image 181
Rebecca Chernoff Avatar answered Jan 04 '23 03:01

Rebecca Chernoff


It's up to you to determine where the reusability lies in your own code. But it's easy enough (and a good idea) to create a library of often-used functions. Create a file like mylib.js, for instance, with things like...

function saveUser(f)
{
    //...
    f.method = 'POST';
    f.action = f.submit();
}

add this to your pages:

<script type="text/javascript" src="mylib.js"></script>

add code your events like this:

<s:link view="/User.xhtml" onclick="return saveUser($('user'));">

Notice that the library code avoids any dependencies on the layout or naming of elements on the pages that use it. You may also want to leave little comments that will remind your future self what the purpose and assumptions of these library functions are.

like image 43
Eric Mickelsen Avatar answered Jan 04 '23 02:01

Eric Mickelsen