0

I'm trying to make a plugin JSLint proof and am struggling with the following error message:

Don't make functions within a loop.

which complains about this snippet:

 for ( i = 0; i < pops.length; i++){
    pops.eq(i)
        .addClass('reverse out '+trans)
        .hide('fast')
        .removeClass('ui-panel-active')
        .find(".ui-page-active")
           .not("div:jqmData(show='first')")
           .removeClass('ui-page-active').end()
        .find(".ui-btn-active")
           .removeClass('ui-btn-active').end()
        .find('div:jqmData(external-page="true")')
           .remove().end().end()
           .delay(350)
           // the problem
           .queue(function(next){
               $(this).removeClass('reverse out pop slide');
                 next();
                 });

            ...
        }

I understand where the problem is, but no idea how to make it JSlint-compliant.

Question:
How do I get the function out of the loop?

Thanks!

frequent
  • 27,643
  • 59
  • 181
  • 333

2 Answers2

5

I think it's time to split up this one-liner. It's ridiculously long.

To move your function out of the loop, literally move the function out of the loop:

function queue_callback(next) {
    $(this).removeClass('reverse out pop slide');
    next();
}

And then replace the anonymous function in the .queue() callback with this:

.queue(queue_callback)
Blender
  • 289,723
  • 53
  • 439
  • 496
  • ya. Thinking about this too :-) – frequent Oct 28 '12 at 23:00
  • Agree with the one-liner, you're traversing the DOM constantly on each loop. If you cache the elements you'll get way better performance. Try detaching them do whatever and then inserting them in DOM again. – elclanrs Oct 28 '12 at 23:01
  • ok. Just tried this. I'm getting a `strict` violation, I guess because of `$(this)`, is it? – frequent Oct 28 '12 at 23:03
  • `Strict violation` on `$(this).removeClass('reverse out pop slide');` – frequent Oct 28 '12 at 23:06
  • @frequent: This seems to be a pitfall of using JSHint: http://stackoverflow.com/questions/11664958/jquery-callback-strict-violation. The error message is somewhat valid, but since you aren't using `queue_callback` outside of this context, the error message isn't really applicable. – Blender Oct 28 '12 at 23:10
  • hm. Ok. `JSLint` sure is picky... :-) – frequent Oct 28 '12 at 23:12
3

The easiest way I can think of is to declare the function outside and pass it as parameter:

var queue = function(next) {
  $(this).removeClass('reverse out pop slide');
  next();
};

...

.queue(queue)
elclanrs
  • 92,861
  • 21
  • 134
  • 171