【问题标题】:Coffee script : using "constructed" string to call a method咖啡脚本:使用“构造”字符串调用方法
【发布时间】:2012-05-12 13:01:20
【问题描述】:

我正在尝试使用由可变数量的用户输入字段组成的字符串,在 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 中实现它的答案。

感谢您的宝贵时间。

【问题讨论】:

    标签: methods coffeescript dojox.gfx


    【解决方案1】:

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

    "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)
    

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

    【讨论】:

    • 谢谢你的明智回答,伙计。让我挖得更深了。现在我真的看到了!你的猜测太棒了——我将数据存储在一个数据库中,我需要 json 额外内容。
    【解决方案2】:

    试试

    surface[formula].setStroke("red") 
    

    【讨论】:

    • 感谢您的回答,但我认为 '[]' 是对数组元素的引用,在我的情况下,字符串“公式”替换了方法的字符串值,在实例上调用'表面' 。类似于:surface.formulaMethod.setStrike "red"。例如,绘制一个矩形:surface.createRect({x: 20,y: 30,width: 100,height:200}).setStroke "red"。
    • 你也可以使用键来访问对象,我认为这就是你想要做的
    • 您说得对,先生。当我被引导阅读几篇关于 js 'apply' 的文章时,现在似乎更清楚了。我会尽快发布已解决的任务。
    【解决方案3】:

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

    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[method]是通过key访问对象。

    再次感谢您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-16
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多