JonoB
JonoB

Reputation: 5897

Javascript and jquery Namespaces

At the moment, I have a whole bunch of html + php files with a $(document).ready function in each.

I believe that the way to go is to collate as much of my JS as possible into a single file, and that I will need to namespace the functions.

So, if I have a php file called product_edit, then I would do something like the following:

<script type="text/javascript"> 
    $(document).ready(function(){
        productActions.documentReady(); 
    });
</script>

And then in my single site_scripts file, I could do something like this:

var productActions = {
    documentReady: function() {
        $('#date').change(function() {
            someGlobalFunction();
            productActions.getTerms();
        });

        $('#product_id').change(function() {
            productActions.getTerms();
        }); 
    },

    getTerms: function() {
        //do something here
    }
};

Firstly: Am I going about this in the right way? Is this overall methodology on the right track...or it is nonsense?

Secondly: it seems that my site_scripts file gets cached, so I have to clear my browser cache every single time I make any changes to it. Are there any quick ways around this?

Upvotes: 1

Views: 449

Answers (3)

albanx
albanx

Reputation: 6333

For you second problme user web developer toolbar and disable cache while developening. If you want to update the javascript file every time the client opens the page, just do something like this when append the js file the html:

<script type="" src="some.js?var=somerandvars" />

Upvotes: 0

Jamund Ferguson
Jamund Ferguson

Reputation: 17024

No need to wrap it in an extra function (as the commenters have said)

$(document).ready(productActions.documentReady)

There a lot of different ways to handle caching. For example you may want to put a timestamp on the file when it was saved (we do this automatically in a build script) and then apply far-futures expires headers so it's only downloaded once.

Also, for your namespace, it's pretty common practice to have a global namespace in all caps. I work at i.TV and we do something like this:

window.ITV = {pages:{}}
ITV.pages.tvListings = {
   init: function() { } // basic init for page
   prop1: "bla bla bla"
} 

And then we can do some fanciness and in your php do something like this, which is completely re-usable across all of your pages:

var pageName = "<?= $pageName ?>";
if (ITV.pages[pageName]) $(document).ready(ITV.pages[pageName].init);

Upvotes: 1

Alex
Alex

Reputation: 35407

1 - Your going in the right direction...

2 - ctrl+F5 performs a "hard-refresh" downloading all resources again...

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Upvotes: 0

Related Questions