Use recursion instead of EVAL

I have a list of elements on the page that should be hidden in the sequence, but right after the previous element was completely hidden.

I did the following code, where I create a large string by inserting callbacks inside previous callbacks, and then use eval to execute the effects, but despite the code working fine, as expected, I'm absolutely sure that this is not the best way to do this.

// get items to hide
    var itemsToHide = jQuery(".hide");

// function responsible to hide the item
    var hideItem = function (item, callback) {
     jQuery(item).hide(100, callback)
    };

// declare an empty function, to be the first to be called
    var buff = function(){};

    for (var i = 0; i < itemsToHide.length; i++) {
// put the previous value of buff in the callback and assign this to buff
     buff = "function(){hideItem(itemsToHide[" + i + "], " + buff + ");}";
    }

// execute the effects
    eval("(" + buff + ")()");

Any suggestion on how to accomplish this effect using recursion without an "evil" eval?

+3
source share
2 answers

Hidden with recursive-functional style

, , .

, , , .

, .

1.

<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
    $(function() {
        var items = jQuery(".to-hide");
        (function hideRec() {
            if (items.length == 0) {
                window.alert("The end.");
                return;
            }
            var toHide = jQuery(items[0]);
            items = items.slice(1);
            toHide.hide("100", hideRec);
        })();
    });
<script>

<ul>
    <li class="to-hide">...</li>
    <li class="to-hide">...</li>
    <li class="to-hide">...</li>
    <li class="to-hide">...</li>
    <li class="to-hide">...</li>
<ul>

2. ?

jQuery , , to-hide.

, - (function() { ... })();. , , .

, , - , , JavaScript - :

(function() {                            // Anonymous function without a name
    if (items.length == 0) {
        window.alert("The end.");
        return;
    }
    var toHide = jQuery(items[0]);
    items = items.slice(1);
    toHide.hide("100", arguments.callee); // Recursive call to anonymous function
})();

, arguments.callee , .

- .

hideRec items. , - , toHide ( jQuery).

jQuery, , - jQuery , .

, .

!

+7

, , :

jQuery(".hide").each(function(i)
{
    var obj = $(this);
    setTimeout(function() { obj.hide(100); }, i * 100);
}
+3

Source: https://habr.com/ru/post/1723127/


All Articles