views:

73

answers:

8

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?

A: 

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

var projID;
Sadat
A: 

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

Māris Kiseļovs
A: 

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

Amit
A: 

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);
}
Lèse majesté
A: 

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);

        });
Claude Vedovini
+4  A: 

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');
jAndy
hey jAndy ,,, can u please show us sample code??? its will be helpful for understand. Thanks a lots...
Amit
G8t Thanks a lots.
Amit
jAndy can u please give me some brief detail about base in your_application.i mean whats the purpose of it here?thanks
Amit
@Amit: You may never forget in javascript, there may be several other scripts that are loaded into a page. So storing data globally is just awful. Your variables can get overwritten which would break your app, etc. So a good plan is, to store your app data locally and even better, protect/hide them within a closure construct.
jAndy
nice one. Thanks a lots. andy.
Amit
Hi Andy, how would you check if the data() store id exists?
WiseDonkey
@WiseDonkey: `if(typeof $.data(document.body, 'projID') !== 'undefined') {}`
jAndy
A: 

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>
Reigel
A: 

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'));​
RobertPitt
@RobertPitt: sure possible, but all variables are still `public` accessible.
jAndy