0

情况:

我有一个名为 DrawLogic 的类,它看起来像(在咖啡脚本中):

 class DrawLogic
    mark: => 
        do something
    etc ....

 @DrawLogic = new DrawLogic 

稍后在 HTML 页面中,我创建“动态常量”,即来自服务器程序的名称,我只想使用/键入/只有一次

<script>
DrawLogic.NameSpaceName='orion42'; 
.... 
</script> 

到目前为止一切都很好,并且正在工作

现在为我的 (svg) 元素扩展 jQuery(在我的类 DrawLogic 中)

class DrawLogic 
   ....
   init: ->
      jQuery.fn.td_data = (attr_name) ->  #look at the '->'
          do something with 'this' 
           #the element of selector works fine     
           #to use the "DrawLogic.NameSpaceName" pseudo constant
           #i have to write:

          window.DrawLogic.NameSpaceName #was orion42 before

   etc...

我在我的“DrawLogic 类”中,如果我在类范围内使用 '=>' i 并且 this 或 (@) 适合this.NameSpaceName(而不是window.DrawLogic.NameSpaceName),但我松散了选择器的“元素”。

又怎样?有没有比使用“window.DrawLogic.NameSpaceName”更好的解决方案来引用我所在的类?我不想重复我自己...

说清楚,我只需要输入 4 次“DrawLogic”(3 次在 coffescript 中,一次在 HTML 中,但现在我必须在 jQuery 扩展函数中的每个引用中使用它:-(

有更好的解决方案吗?

4

1 回答 1

1

当您说您在里面时,您并不完全正确DrawLogic

class DrawLogic 
    init: ->
        jQuery.fn.td_data = (attr_name) ->
            # Here you're not really inside DrawLogic anymore.

无论调用者说你在里面td_data,你都在里面,这是标准的 JavaScript 行为。以上等价于:

f = (attr_name) -> #...
class DrawLogic
    init: -> jQuery.fn.td_data = f

init除非你有使用的局部变量td_data

如果window.DrawLogic.NameSpaceName太多,那么您应该能够使用DrawLogic.NameSpaceName或使用闭包:

class DrawLogic
    init: ->
        DL = @constructor
        jQuery.fn.td_data = (attr_name) ->
            # Use DL.NameSpaceName in here
于 2013-11-11T21:52:00.427 回答