javascript - How to transform a String "a,b,c,d..." into a.b(c,d,...); for execution -
i have small multiplayer app working in websockets. application composed of game , chat object, each specific methods.
basically, client receives message string formatted : "object,method,arg1,arg2"
, example "chat,newmsg,foo bar", or "game,addplayer,name,level,team". first example should translated chat.newmsg("foo bar");
while second example game.addplayer(name,level,team);
having difficulties doing writing message reader.
i trying figure out elegant solution, :
var msgreader = function(message){ msg=message.split(","); msg[1].apply(msg[0],msg[2]); }
but message can have many arguments, , can't quite figure out how handle that. me? not use eval() ^^
apply()
expects array of arguments; if want pass arguments individually, use call()
.
however, apply()
best in (in right use case), don't know number of arguments.
var msgreader = function (message) { var props = message.split(","); var obj = window[props[0]]; obj[props[1]].apply(obj, props.slice(2)); };
apply()
expects scope first parameter, provide obj
. see documentation apply()
, slice()
, split()
.
this pass strings
name
,level
,team
etc, rather value of variables have names.this only work if object wish invoke methods on global object.
if object wish target (
a
) isn't global, property on another object (b
), changewindow
referenceb
.var msgreader = function (message) { var props = message.split(","); var obj = b[props[0]]; obj[props[1]].apply(obj, props.slice(2)); };
otherwise, you'll have either make object global, or add property object.
Comments
Post a Comment