Loading ...
Sorry, an error occurred while loading the content.

Re: [jslint] Don't make functions within a loop -- what is the preferered pattern?

Expand Messages
  • Joshua Bell
    ... I believe JSLint is carping because the outer anonymous function is effectively being redefined each time through, even though the definition is static
    Message 1 of 5 , Feb 1, 2011
    • 0 Attachment
      On Tue, Feb 1, 2011 at 12:36 PM, saj14saj <saj14saj@...> wrote:

      > I have noticed recently that jslint is now giving a problem warning when
      > creating functions in a loop.
      >
      > Below is an example use case, I am creating a rows in a table and
      > linking events to each row (using the Dojo toolkit, but the Dojo'isms in
      > the code should be self-explanatory.
      >
      > I use the closure to preserve the index value to make the event
      > processing easier.
      >
      > What pattern is recommended, if jslint considers this to be a
      > problematic practice?
      >

      I believe JSLint is carping because the outer anonymous function is
      effectively being redefined each time through, even though the definition is
      static across iterations. You can restructure your code and maintain the
      closure over the index by pulling the anonymous function definition out of
      the loop and naming it, e.g. something like:

      function bind_onclick(index) {
      return function() {
      that._onRowClick(index);
      };
      }

      for (r = 0; r < this.data.length; r += 1) {
      console.log('r', r);
      tr = dojo.create('tr', {
      'class': r === this.selectedIndex ? 'selected' : '',
      'onclick': bind_onclick(r)
      }, this.tbodyNode, 'last');
      ... etc ...
      }

      That's not necessarily as concise, but it is what JSLint is looking for.


      [Non-text portions of this message have been removed]
    • saj14saj
      ... Thank you, that makes a lot of sense; it didn t occur to me that JSLint was fussing about the outer function, rather than the inner... I will try that
      Message 2 of 5 , Feb 1, 2011
      • 0 Attachment
        > I believe JSLint is carping because the outer anonymous function is
        > effectively being redefined each time through, even though the definition is
        > static across iterations. [ .... ]

        Thank you, that makes a lot of sense; it didn't occur to me that JSLint was fussing about the outer function, rather than the inner...

        I will try that tomorrow when I am back at work...
      Your message has been successfully submitted and would be delivered to recipients shortly.