开发者

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

This partial code I hacked in to JamieMThomas's JQuery plugin that combines the Microsoft JQuery template and linking plugins together (declarative linking in the templates). I wanted to reference a variable tree like "A[0].B[0].C[0].myProperty". You can skip down to the bottom as I just put this in 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(/([A-Z]+)\[\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(/[A-Z]+/);                         // array's 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 eval at the bottom ends up running the below code. 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;


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

The rest is here: How to turn this JavaScript string "myArray[0].myPrice" in to a reference to myPrice?

Basically:

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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜