waxical
waxical

Reputation: 3896

jQuery - sharing vars between functions

This should be fairly simple; i'm pretty sure I've just not understood it.

FYI, the website is using jQuery to run ajax .load() on content.

On my main parent page, in the header I have my nav .load() jQuery code:-

<script type="text/javascript" charset="utf-8">

    $(document).ready(function(){

        $('a.nav').click(function() {
            page = $(this).attr('page');
            projID= $(this).attr('projID');

            if($("#mainRight").is(":visible")) { $('#mainRight').hide(200); }

            switch(page) {

            case 'projSettings': $("#mainRight").load("content.php?load=" + page, { projID: projID}); break;
            case 'projMetrics': $("#mainRight").load("content.php?load=" + page, { projID: '5000227' }); break;
            case 'projTags': $("#mainRight").load("content.php?load=" + page, { projID: projID}); break;
            case 'projShare': $("#mainRight").load("content.php?load=" + page, { projID: '5000227' }); break;

            }
            $('#mainRight').show(300);

        });

Now, basically I want the projID to be rememebred for use by other a.nav clicks that don't supply it.

An linked anchor calling this looks like <a page="projSettings" projID="522" class="nav">Settings</a> and I'd it to save that 522. So, other requests (that don't have the projID, as the data has been loaded into the DOM for other navs and they don't know the projID. I hope that makes sense.

So, I'd like to know how to have links like <a page="projSettings" class="nav">settings</a> when the projID has already been used in the previous call.

Any thoughts?

Upvotes: 2

Views: 1053

Answers (8)

RobertPitt
RobertPitt

Reputation: 57268

Would prototypes not be better to do this with?

such as

function System()
{
    settings = {
       'Foo': 'Bar'
    }
}

//Then define a prototype
System.prototype.getSetting = function(key)
{
   return settings[key] || undefined;
}


System = new System();
alert(System.getSetting('Foo'));​

Upvotes: 0

jAndy
jAndy

Reputation: 235982

Well, ironically you're already saving projID globally (better said, within the window object by not using var in your declaration.

So you already can access projID from everywhere in your code, once it's initialized.

Anyways this is not a good pratice, opposite, it's a very bad pratice.

The best way I can think of is to create you own application object where you store all your data and access it from there.

var your_application = {
    var foo  = 'bar',
        base = 'ball';        
};

// your_application.foo = 'another bar';

You can push this principle pretty far with using closures and functional programming. An even better solution to store and keep data local and not global (window) could look like

var your_application = function(){
    var foo  = 'bar',
        base = 'ball';  

    return {
        getfoo: function(){
            return foo;
        },
        setfoo: function(newfoo){
            foo = newfoo;
        }
    };
});

var app = your_application();
app.setfoo('foobar!');
alert(app.getfoo());

That is the idea of methodical javascript programming. There a some good books out there, I would recommend to start of with Javascript: the good parts by Douglas Crockford.

Another solution for this should be the jQuery .data() method, which is capable of storing data in a global hash.

// store
$.data(document.body, 'projID', projID);

// access
var foo = $.data(document.body, 'projID');

// remove
$.removeData(document.body, 'projID');

Upvotes: 6

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

try this, and I made your codes more simple..

<script type="text/javascript" charset="utf-8">
    var projID; // making it global
    $(document).ready(function(){

        $('a.nav').click(function() {
            page = $(this).attr('page');
            projID= $(this).attr('projID');

            if($("#mainRight").is(":visible")) { $('#mainRight').hide(200); }                

            switch(page) {

            case 'projMetrics': projID = '5000227'; break;
            case 'projShare': projID: '5000227'; break;

            }

            $('#mainRight').load("content.php?load=" + page, { projID: projID}, function(){
                   $(this).show();
            });

        });
     })
</script>

Upvotes: 0

Claude Vedovini
Claude Vedovini

Reputation: 2481

I have not tested it but the following modification should make it:

<script type="text/javascript" charset="utf-8">
    var projID = null; // Better to have some default here

    $(document).ready(function(){

        $('a.nav').click(function() {
            var page = $(this).attr('page');
            projID= $(this).attr('projID') || projID;

            if($("#mainRight").is(":visible")) { $('#mainRight').hide(200); }

            switch(page) {

            case 'projSettings': $("#mainRight").load("content.php?load=" + page, { projID: projID}); break;
            case 'projMetrics': $("#mainRight").load("content.php?load=" + page, { projID: '5000227' }); break;
            case 'projTags': $("#mainRight").load("content.php?load=" + page, { projID: projID}); break;
            case 'projShare': $("#mainRight").load("content.php?load=" + page, { projID: '5000227' }); break;

            }
            $('#mainRight').show(300);

        });

Upvotes: 0

L&#232;se majest&#233;
L&#232;se majest&#233;

Reputation: 8045

If I understand you correctly, you have one function that is being applied as .click() handler for various a.nav elements, and you want the projID variable to only have to be set once and remembered for future calls of that same function.

This seems like the perfect use case for static variables. A static variable will retain its value between function calls, but is still scoped within that function. JavaScript doesn't have explicit static variables per se, but you can simulate them by defining a variable as a member of that function; the end result is the same. Here is the code from that link:

function countMyself() {
    // Check to see if the counter has been initialized
    if ( typeof countMyself.counter == 'undefined' ) {
        // It has not... perform the initilization
        countMyself.counter = 0;
    }

    // Do something stupid to indicate the value
    alert(++countMyself.counter);
}

Upvotes: 0

Amit Soni
Amit Soni

Reputation: 3316

Yes Make it global variable. Add var projID; at starting of script. Agreed with Sadat.

Upvotes: 0

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17285

Just define variable outside a function and it will become global.

Upvotes: 0

Sadat
Sadat

Reputation: 3501

Just type the following line at start of your js script-

var projID;

Upvotes: 0

Related Questions