JSON is being globally modified in my JavaScript... why?
Below are some functions i have that use the official jQuery Template plugin and insert some JSON my backend devs are giving me in the var
s topPages
and lates开发者_Go百科tPages
but for some reason when i call the insertOrHideList()
function and then call the normal renderList()
function it's carrying over the max
attribute for some reason. So, instead of getting 100
results (see 2nd line of renderList()
im getting 5
see the insertOrHideList()
calls at the bottom)
Any ideas?
function renderList(json,max){
if(!max){max=100}
tempjson = json;
tempjson.length = max;
the_template = $.template(null, '<li><a href="{{if CONTENT_ID}}article/${CONTENT_ID}{{else}}${CATEGORY_TREE_ID}{{/if}}" title="Go to the ${TITLE} page">${TITLE}</a></li>');
return $.tmpl(the_template,tempjson);
}
function insertOrHideList(selector,json,max){
if(!max){max=5}
if(typeof json !== 'undefined' && json.length >= 5){
$(selector).append(renderList(json,max));
}
else{
$(selector).parent().remove();
}
}
insertOrHideList('.most-popular ol',topPages,5);
insertOrHideList('.recently-added ol',latestPages,5);
console.log(renderList(latestPages));
When you do this:
tempjson = json;
That global tempjson
array is set to the same reference as your json
(latestPages
), so changes you're making to it, are made to the original. To get a new array to work with, you need to make a copy, like this:
var tempjson = json.slice(0);
Note the var
addition, so that we're not creating a global variable either (a separate issue here).
Looks like you're passing max through on this line:
$(selector).append(renderList(json,max));
which will be 5, from the calls to insertOrHideList. Are you actually after:
$(selector).append(renderList(json,json.length));
?
if(typeof json !== 'undefined' && json.length >= 5){
$(selector).append(renderList(json,max));
}
should be:
if(typeof json !== 'undefined' && json.length >= max){
$(selector).append(renderList(json,json.length));
}
精彩评论