JavaScript acrobatics: this code uses eval, how to remove it?

This is the partial code that I cracked in the JamieMThomas JQuery plugin that combines the Microsoft JQuery template and binds plugins together (declarative binding in templates). I wanted to refer to a tree of variables, for example "A[0].B[0].C[0].myProperty" . You can skip down as I will just put this for reference:

 var extVar = $.extend({ name: elem.name }, { convert: binding.converter.convertBack, convertBack: binding.converter.convert }); // binding.field is a string pointing to a variable to map var a = binding.field.match(/([AZ]+)\[\d+\]/g); // Find all array references // If we have arrays, we need to create the corresponding hierarchy in "mapping" if ( a != null) { b = mapping; // mapping (object) will reference a variable to map for( i = 0; i < a.length; i++) // for each array found { var arr = a[i].match(/[AZ]+/); // array name b[arr] = []; // make mapping match our binding.field text var idx = a[i].match(/\d+/g); // index value if( a[i+1] !== undefined ) // is the next item an array? b[arr][idx] = []; // Yes, match the array else b[arr][idx] = {}; // No, match an object b = b[arr][idx] ; // Reference LPC[x] // reference the next child } } eval('(mapping.' + binding.field + ' = eval("extVar") )'); 

This sign at the bottom ends up working under the code below. How would you rewrite this to not include the eval statement?

 mapping.A[2].B[1].C[5].myProperty = A[2].B[1].C[5].myProperty; 
+4
source share
1 answer

In javascript, as you can do object[propertyName] to read things, you can do object[propertyName] = value to assign material.

The rest is here: How do I turn this JavaScript string and myArray [0] .myPrice "into a link to myPrice?

Mostly:

 var data = mapping, chain = binding.field.split(/[\.\[\]]+/); // If the last character of binding.field is `]` we'll get "" in the end of chain if (!chain[chain.length - 1]) { chain.splice(-1); } var n = chain.length; for (var i = 0; i < n - 1; i++) { data = data[chain[i]]; } data[chain[n - 1]] = extVar; // Embrace JavaScript Awesomeness! 
+4
source

All Articles