0

How would this code be refactored to use jQuery?

function emleProcessOnLoad(aThis) {
  var result = document.evaluate("//span[@class='emleOnLoad']",
    aThis.document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  for (var jj=0; jj<result.snapshotLength; jj++){
    eval("var emleThis=result.snapshotItem(jj);" + result.snapshotItem(jj).textContent);
  }
}

There appears to be four issues for jQuery to address:

  1. Context: aThis.document
  2. Selection: //span[@class='emleOnLoad']
  3. Iteration: for (var jj=0; jj<result.snapshotLength; jj++)
  4. Value: .textContent

The code is a fragment from Emle - Electronic Mathematics Laboratory Equipment JavaScript file emle_lab.js.

The .evaluate() function grabs all of the <span> tags which have class emleOnLoad. The resulting text content contains an expression fragment such as:

emleHandleInput(emleThis.parentNode.parentNode,"EMLE_CET_PROPER_FRACTION");

which is appended to:

var emleThis=result.snapshotItem(jj);

and then is executed for each item found by the .evaluate() function.

CW Holeman II
  • 4,661
  • 7
  • 41
  • 72
  • Eval is Evil! Be very careful when using eval, especially if your source is not trustworthy. – Andreas Grech Mar 28 '10 at 14:03
  • The current effort is to refactor Emle with jQuery which at this point has reduced LoC by 30%. I have added Eval-Is-Evil blueprint to the Emle project: https://blueprints.launchpad.net/emle/+spec/eval-is-evil – CW Holeman II Mar 29 '10 at 03:00
  • On the other hand, if the source *is* trusted, there is nothing inherently wrong with eval. – noah Mar 29 '10 at 18:19
  • Moved namespace component of question to: http://stackoverflow.com/questions/2572304/what-is-jquery-for-document-createelementns – CW Holeman II Apr 03 '10 at 21:07

2 Answers2

1

The main loop can be simplified down to this

$("span.emleOnLoad").each(function() {
   var content = $(this).text();
   // do something with content
});

but the whole idea needs some rethinking. Store chunks of javascript in spans and eval them at run time - this is quite weird.

user187291
  • 53,363
  • 19
  • 95
  • 127
0

You don't need jQuery for this, but I would replace the switch with this:

var lu = (function() {
   var TYPES = { // call it whatever you want
    'xhtml':'http://www.w3.org/1999/xhtml',
    'math': 'http://www.w3.org/1998/Math/MathML',
    'svg': 'http://www.w3.org/2000/svg'
  };
  return function luf(aPrefix){
    return TYPES[aPrefix] || '';
  };
})();

First, I create an anonymous function and call it so that I can declare local variables, otherwise TYPES will end up in (presumably) global scope. Then I create an object (map/hash) that maps the values just like your switch would. Finally, create another anonymous function that looks the prefix up in TYPES and defaults to ''.

The rest is pretty messed up.

noah
  • 21,289
  • 17
  • 64
  • 88