Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  109] [ 1]  / answers: 1 / hits: 18846  / 13 Years ago, mon, april 25, 2011, 12:00:00

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!


More From » ajax

 Answers
12

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.


[#92579] Friday, April 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikhilh

Total Points: 224
Total Questions: 89
Total Answers: 99

Location: Bahrain
Member since Fri, Sep 16, 2022
2 Years ago
;