我有一个定义任务的 XML 文档,该任务是要对某些数据执行的操作的列表。我需要将此“任务列表”转换为可以在以后调用的 Javascript 方法,该方法又会调用一系列带有适当数据的预定义方法。您将如何实现这一目标?
重要说明:
我不担心 XML 解析。我对如何实际构建任务方法更感兴趣,包括将基本数据绑定到预定义的操作方法。这就是我正在努力的部分。
编辑:我已经修改了我的示例,使其更有趣,并希望更清晰一些。
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] = /* ??? */;
}
当我parseTask()
在<task id="enter-castle">
节点上调用时,这应该创建一个函数,实际上,调用时会执行以下操作:
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.");
}
}