Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing JS variables in multiple <script> blocks

I'm working on a CodeIgniter application.

I have a view, let's call it Calendar, which has a JS/jQuery <script> block in it. Looks like this:

    $(document).ready(function()    {

        $("#day_list").fadeIn(600);

        // init
        var current_month = <?= $init['current_month']; ?>;
        var current_year = <?= $init['current_year'] ?>;

        // previous, next month ajax call
        $(".previous, .next").click(function(event) {
            // do stuff to these variables, then ajax call.
            $.ajax({
                // ajax
            });
        });
    });

In another view, my footer, I have another script block which should use the same variables (current_month and current_year). However, it doesn't know about their existence. What would be the quickest, and easiest, way to pass these variables from the first <script> block to the other? I can't put the two blocks together because of the way my application is build. Should I just write a function for it which gets and returns these values (and how should I do this? I'm such a newbie) or is there an easier way?

Thanks a lot!

like image 798
Joris Ooms Avatar asked Apr 25 '11 17:04

Joris Ooms


1 Answers

It's really important to learn to namespace your variables in JavaScript. Scope matters, and it matters a lot. Right now because you're using the "var" keyword, your stuff will be in the local scope.

Some of the other answers here say that you should move them into the global scope. That works, unless something else overwrites them unintentionally. I highly disagree with this approach, globally scoped variables are bad practice in JavaScript.

Namespacing works like this:

var foo = foo || {} //Use existing foo or create an empty object.
foo.bar = foo.bar || {}
foo.bar.baz = foo.bar.baz || {}

etc. etc.

This may seem like a lot more work, but it also PROTECTS YOUR VARIABLES.

You can also add a simple namespacing function that safely namespaces everything against the window object. (I cribbed this from somewhere ages ago, and I think I modified it a little but maybe didn't).

Put this at the top of your app and you can namespace stuff with $.namespace("myapp.mydata") and then say myapp.mydata.currentYear = ...

$.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

Also, if you're new, or want to get hardcore, I recommend reading JavaScript the Good Parts by Crockford.

like image 126
JSager Avatar answered Oct 10 '22 02:10

JSager