咖啡脚本:使用“构造”字符串来调用方法

时间:2012-05-12 13:01:20

标签: methods coffeescript dojox.gfx

我正在尝试通过使用由可变数量的用户输入字段构成的字符串来调用Coffee脚本中的类实例上的方法。假设我们有一个“表面”实例,我们应该在其上调用绘制特定数字的方法。以下是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

我已经看到了所有类似的问题,但我找不到在Coffee Script中实现它的答案。

感谢您的时间。

3 个答案:

答案 0 :(得分:2)

所以你有一个像这样的字符串:

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

并且您想将createRect称为surface上的方法,对吧?你通过将它们拼凑成一根绳子,使你的生活变得更加艰难和丑陋;相反,您应该创建两个单独的变量:一个用于保存方法名称的字符串和一个用于保存参数的数组:

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

然后您可以使用Function.apply

surface[method].apply(surface, args)

如果您需要将方法名称和参数存储在某个数据库中(或通过网络传输它们),请使用JSON.stringify生成结构化字符串:

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

然后JSON.parse解压缩字符串:

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

不要丢弃已有的结构,维护该结构并利用它,这样您就不必浪费大量时间和精力来解决已经解决的解析任务。

答案 1 :(得分:1)

尝试

surface[formula].setStroke("red") 

答案 2 :(得分:1)

我今天很开心!我已经学会了如何构造调用类实例上的方法的字符串。看起来很简单(先生MU先生给我看的时候):

method = "stringMethodToCall"  # selected by user's input  
arguments = [arrayOfValues] # must be array or array-like object
surface = dojox.gfx.createSurface("dojocan", 500, 400) 

现在:

surface[method].apply(surface,arguments)

就像先生一样。 CODEMONKEY说,surface [方法]正在按键访问对象。

再次感谢你。

相关问题