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:
- pass in object directly closure.
- 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
Post a Comment