Question

I have an XML document that defines a task, which is a list of actions to be performed on certain data. I need to convert this "task list" to a Javascript method which can be called at some later time, which in turn calls a series of pre-defined methods, with the appropriate data. How would you achieve this?

Important Clarification:
I'm not worried about the XML parsing. I'm more interested in how to actually build the Task Method, including binding the essential data to the pre-defined action methods. That's the part I'm struggling with.

Edit: I've revised my example to make it a bit more interesting, and hopefully a bit clearer.

XML:

<task id="enter-castle">
    <if holding="castle-key">
        <print message="You unlock the castle door and enter." />
        <destroy item="castle-key" />
        <goto location="castle" />

        <else>
            <print message="The castle door is locked." />
        </else>
    </if>
</task>

Javascript:

Game = {

    print: function(message) {
        // display message
    },

    destroy: function(item) {
        // destroy the object
    },

    goto: function(location) {
        // change player location
    },

    ifHolding: function(item) {
        // return true if player has item
    }
};

parseTask(taskNode) {

    var taskId = taskNode.getAttribute('id');

    // What goes here??

    Game.tasks[taskId] = /* ??? */;
}

When I call parseTask() on the <task id="enter-castle"> node, this should create a function that, in effect, does the following when called:

Game.tasks.enterCastle = function() {
    if (Game.ifHolding('castle-key')) {
        Game.print("You unlock the castle door and enter.");
        Game.destroy('castle-key');
        Game.goto('castle');
    } else {
        Game.print("The castle door is locked.");
    }
}
Was it helpful?

Solution

What you want are closures.

function createMethod(arguments) {
    var task = doSomethingWithYour(arguments);
    return function(xmlData) { // <- this is the fundamental part
        // do the task with your data
        // the "task" vars are still available
        // even if the returned function is executed in a different context
    }
}

This allows you to create an own method for each task. Don't use the Function constructor or eval.

OTHER TIPS

This is a situation where JavaScript's eval() function will make your life much easier. You can easily build a JavaScript source string matching your desired one and evaluate it to assign the function to the desired property of your Game object.

Of course, there are drawbacks to using "eval", which I won't explore in this answer since you can find countless justifications for why not to use it on the web. However, building and evaluating a simple JS source string will be much easier in the short term than say, a closure based solution, despite any potential drawbacks of performance and security. Moreover, the "eval" based solution will be easy to test since you can simply inspect the source string before it is evaluated.

So try something like this:

function buildTaskFunction(taskXml) {
  var source='', depth=0, node /*a visitor to each DOM node*/;
  // foreach (node in traverseInOrder(taskXml)) {
    switch (node.nodeName) {
      case 'TASK':
        source += 'Game.tasks.' + makeFunctionName(node.id) + '= function(){';
        depth++;
        break;
      case 'IF':
        source += 'if(' + getConditionalAttribute(node) + '){'
        depth++;
        break;
      case 'ELSE':
        source += '}else{';
        break;
      case 'DESTROY':
        source += 'Game.destroy("' + node.getAttribute('item') + '");'
        break;
      case 'PRINT':
        source += 'Game.print("' + node.getAttribute('message') + '");'
        break;
      // case etc...
      default: throw new Error('unhandled node type "' + node.nodeName + '"');
    }
  // end "foreach node".
  while (depth-- > 0) { // You'll need to account for nested "if"s somehow...
    source += '}';
  }
  eval(source);
}

And again, there are many potential problems (not definitive ones) with using "eval", so please do read about and try to understand them in the context of your solution. Use your own judgement when deciding if the drawbacks are worth the benefits in your own program -- just because a tool can be dangerous doesn't mean you should not use it.

Example using dojo:

dojo.require("dojox.xml.parser");

dojo.ready(function(){
  // Parse text and generate an XML DOM
  var xml = "<tnode><node>Some Text</node><node>Some Other Text</node></tnode>";
  var dom = dojox.xml.parser.parse(xml);

  var docNode = dom.documentElement();
  // ...
}

The remainder of the function is non-trivial, but would largely just consist of attribute lookup using ['<attribute-name>'] and child node iteration using dojo.forEach(<node>.childNodes, function(childNode) { /* do stuff */ });

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top