开发者

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_开发者_Go百科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!


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.


Declare the variables as global. Just move them outside of the document ready function.

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

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

current_month and current_year can now be accessed from any script block.


If you declare your variables outside of any function block, they will be global variables, available to any script on the page.

var current_month;
var current_year;

$(document).ready(function () {

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

    ...etc...

});


The "var" declaration initializes both variables (current_month, current_year) in the ready function scope - thus they are not available elsewhere. You can declare them globally:

var current_month;
var current_year;
$(document).ready(function()    {
    ...
    current_month = ...
}

That way you can use them in the bottom script.


Since you var declared these variables inside of a function, they have local scope. Move them outside to make them global:

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

$(document).ready(function()    {

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

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

The better solution than having global variables is to store them semantically in your HTML, then retrieve them through jQuery:

<body data-month="<?= $init['current_month']; ?>" data-year="<?= $init['current_year'] ?>">

$(document).ready(function()    {
    $("#day_list").fadeIn(600);

    var current_month = $("body").data("month");
    var current_year = $("body").data("year");

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜