I am working on cleaning up some adopted code – there is a lot of duplication.
There is a set of jQuery callbacks where we get back JSON like this:
[
{"location":{"id":164,"name":"place 1"},"users":[{"id":1,"name":"joe"},{"id":2,"name":"jack"}]},
{"location":{"id":162,"name":"place 2"},"users":[{"id":3,"name":"joe"},{"id":4,"name":"jon"}]}
]
I go through with these functions:
function locations_view(r) {
str = "";
$.each(r.data, function(k, v) {
str += v.location.name + "<br />";
iterate_users(v.users);
});
$("#locations").html(str);
}
function iterate_users(users) {
str += '<strong>users:</strong>' + users.length + '<br />';
$.each(users, function(k1, v1) {
str += "<a href='/users/" + v1.id + "'>" + v1.name + "</a> ";
});
str += "<br />";
}
This seems to work but it looks a little ugly. Is there a better way to do this. Also, I want to minimize memory consumption (returning the string rather than have a global str was causing performance issues). Is there a better, more elegant way to do this? Would having multiple copies of str ever cause a problem? Like if I have products_view that also uses a str?
Yes, if something else uses
strin the wrong way (i.e. also globally) then that will cause a problem. Best not to have any globals at all. You could change them to this:And that would be much better. If there are other functions that use
iterate_users, they’ll need to be changed too.Also, if you’re not already doing this, consider escaping the HTML in
v1.nameto prevent script injection. You could also use jQuery/DOM manipulation instead.