单身人士在JS / coffeescript中引用自己的优雅方式?

时间:2016-01-15 06:41:24

标签: javascript coffeescript

我正在创建一个由用于存储数据的单例组成的模块:

context =
    c:@
    selected:
        sketch: undefined
        points: []
        edges: []
    hovered:
        points: []
        edges: []
    ###Note: Perhaps later I can make a more elegant naming scheme
    say, specifying subobjects such as context.select.sketch(<sketch>)###
    select:
        sketch: (sketch)->
            c.selected.sketch = sketch
            return
        node: (point)->
            c.selected.points.push point
    deselectAll: ->
        ###Clear all arrays ###
        c.selected.points.length = 0
        c.selected.edges.length = 0

我希望select包含访问selected子对象内的属性的方法。但是,与闭包不同,我无法将this存储在命名变量中,并且我无法在context内访问context.select this参考context.select

如何建立对父/根对象的引用以在子对象中使用?

1 个答案:

答案 0 :(得分:1)

我鼓励您创建没有名称空间的类,以提高可读性。你在这里:

# please use class syntax as a vessel to create singleton
# you may declare class and then call new and assign it's instance to avariable 
# or, since it's a singleton, you can do that in one line
window.Context = new class Context

# constructor function should init the object
constructor: ->
    @selected =
      sketch: undefined
      points: []
      edges: []
    @hovered =
      points: []
      edges: []

    # convenience namespace, just referring to class methods
    @select =
      sketch: @selectSketch
      node: @selectNode

  # not having namespaces adds a lot to clarity of the class
  selectSketch: (sketch) =>
    # no need to call return here
    @selected.sketch = sketch

  selectNode: (point) =>
    @selected.points.push point

  # you probably want to assign new array rather then reset the length 
  deselectAll: =>
    @selected.points = []
    @selected.edges = []