I'm trying to call a method on a class instance in Coffee script by using a string , made from a variable number of user's input fields . Let's say we have a "surface" instance , on which we should call a method for drawing a specific figure . Here is the code in CoffeeScript:
dojo.ready ->
dojoConfig = gfxRenderer: "svg,silverlight,vml"
surface = dojox.gfx.createSurface("dojocan", 500, 400)
/ The user's input values are stored in an array
/ and then concatenated to create a string of this pattern:
/ formula = "createRect({pointX,pointY,height,width})"
/ Now I should apply the string "formula" as a method call to "surface" instance
surface."#{formula}".setStroke("red")
/ ?? as it would be in Ruby , but .... it fails
I have seen all the similar questions , but I cannot find the answer for implementing it in Coffee Script .
Thank you for your time .
So you have a string like this:
and you want to call that
createRect
as a method onsurface
, right? You're making your life harder and uglier than it needs to be by massing it all together into a single string; instead, you should create two separate variables: a string to hold the method name and an array to hold the arguments:Then you can use
Function.apply
:If you need to store the method name and arguments in a database somewhere (or transport them over the network), then use
JSON.stringify
to produce a structured string:and then
JSON.parse
to unpack the string:Don't throw away the structure you already have, maintain that structure and take advantage of it so that you don't have to waste a bunch of time and effort solving parsing tasks that have already been solved.