methodscoffeescriptdojox.gfx

Coffee script : using "constructed" string to call a method


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 .


Solution

  • So you have a string like this:

    "createRect(pointX,pointY,height,width)"
    

    and you want to call that createRect as a method on surface, 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:

    method = 'createRect'
    args   = [ 0, 11, 23, 42 ] # the values for pointX, pointY, height, width
    

    Then you can use Function.apply:

    surface[method].apply(surface, args)
    

    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:

    serialized = JSON.stringify(
        method: 'createRect'
        args:   [0, 11, 23, 42]
    )
    # serialized = '{"method":"createRect","args":[0,11,23,42]}'
    

    and then JSON.parse to unpack the string:

    m = JSON.parse(serialized)
    surface[m.method].apply(surface, m.args)
    

    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.