Using javascript closures for context in loops -


is bad practice make jquery closure purpose of retaining context?

example:

{     testfunction: function() {         //instantiate variables etc...          (var = 0; < columns.length; i++) {             (var j = 0; j < columns[i].length; j++) {                 // create closure .then callback has correct value x                 var func = function() {                     var x = new testobject(columns[i][j].id);                      // find method returns jquery promise                     x.find().then(function() {                         // use x logic here                     });                 };                 func();             }        }    } } 

in case closure needed function jquery promise has context x is. otherwise x variable changed after next iteration of loop. jquery promise object gets value of whatever x in last iteration of loop.

i'm looking best practices here, wondering keep code simple, readable , efficient.

please note performance issues come along closures/not using closures. references appreciated.

using closure practice, can simplify little:

  1. pass in object directly closure.
  2. use iife instead of named function declaration.
for (var = 0; < columns.length; i++) {     (var j = 0; j < columns[i].length; j++) {         (function(x) {             x.find().then(function() {                 // use x logic here             });         }( new testobject(columns[i][j].id) ));     } } 

note: simplify code little using jquery's $.each() method, using regular for loop way faster.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -