This article is clear that we shouldn't use eval()
.
https://24ways.org/2005/dont-be-eval
But I've failed to implement the suggested alternative.
A simple version of what I'm doing:
var list = $('ul.plain-list li');
$('.search-filter button').each(function(){
var d = $(this).data('filter');
$(this).text(eval(d).length);
});
The value of the variable d
matches the names of a set of other variables, for example list
. I'm using eval()
to marry these two things up, which is very effective, but it looks like I shouldn't be doing it.
What is the correct way to do the above without using eval()
?
Edit: I'm not generating variable variables! It looks like I could be using an array or dictionary, but that seems overly-complex, the above code is working very well and is so lightweight.
Edit2: I definitely appreciate the answers, but what I'm thinking is that my usage of eval()
is so specific, just a single string from a piece of static HTML, that the security issues mentioned in the article aren't relevant. Is that fair to say?
Edit3: Still struggling with this I'm afraid. Here's my exact code, if anyone can rewrite it I would be very appreciative.
var all = $('ul.plainList li');
var stories = $('ul.plainList li:not(.type-sjn)');
var sjn = $('ul.plainList li.type-sjn');
$('.search-filter button').each(function(){
var d = $(this).data('filter');
$(this).find('span').text(eval(d).length);
});
In case it's not clear, the values of data-filter
exactly match the var names all
, stories
, sjn
.
What the code does is gets the count of different types of posts, and inserts this count into a button which corresponds to each post type.