views:

186

answers:

2

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.

+1  A: 

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.

stereofrog
Yup. extremelu weird, but he said something about it being math stuff, so showing the evaluated part is propably a feature. A dangerous one :)
naugtur
There is no advantage to using eval here. It doesn't matter if it's "math stuff".
noah
Just need to add the context node, `aThis.document`.
C.W.Holeman II
A: 

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