diff --git a/app/Game/Core/Protocol/Helper.js b/app/Game/Core/Protocol/Helper.js index 90cbb7a..cf31bf2 100755 --- a/app/Game/Core/Protocol/Helper.js +++ b/app/Game/Core/Protocol/Helper.js @@ -1,33 +1,39 @@ define([ - "Game/Core/Protocol/Parser" + "Game/Core/Protocol/Parser", + "Lib/Utilities/Exception" ], -function (Parser) { +function (Parser, Exception) { var Helper = {} Helper.encodeCommand = function (command, options) { - return Parser.encode(Helper.assemble(command, options)); + var message = {}; + message[command] = options || null; + return Parser.encode(message); } - Helper.assemble = function (command, options) { - var commands = {}; - commands[command] = options || null; - return commands; - } + Helper.applyCommand = function(options, target) { - Helper.runCommands = function (message, callback) { - var commands; - if (typeof message == "string") { - commands = Parser.decode(message); + var message; + if (typeof options == "string") { + message = Parser.decode(options); } else { - commands = message; + message = options; } - for(var command in commands) { - callback(command, commands[command]); + // The for loop is only here to get the key, it is not designed to get multiple commands + for(var command in message) { + var methodName = "on" + command.toUpperCaseFirstChar(); + var options = message[command]; + + if (!target[methodName]) { + throw new Exception("Helper.applyCommand:", target, "has no method", methodName); + } + + target[methodName].call(target, options); } - } + }; return Helper; diff --git a/app/Lib/Utilities/Exception.js b/app/Lib/Utilities/Exception.js new file mode 100644 index 0000000..affd2c9 --- /dev/null +++ b/app/Lib/Utilities/Exception.js @@ -0,0 +1,37 @@ +define([ +], + +function() { + + function Exception(/* arguments */) { + var message = []; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (typeof arg == "object") { + var name = this.getTypeOfObject(arg); + message.push(name); + } else { + message.push(arg); + } + }; + + this.message = message.join(" "); + + Error.call(this, this.message); + } + + Exception.prototype = Object.create(Error.prototype); + + Exception.prototype.toString = function() { + return this.message; + }; + + Exception.prototype.getTypeOfObject = function (obj) { + var funcNameRegex = /function (.{1,})\(/; + var results = (funcNameRegex).exec((obj).constructor.toString()); + return (results && results.length > 1) ? results[1] : ""; + } + + return Exception; + +}); \ No newline at end of file