简体   繁体   English

单身人士在JS /咖啡脚本中引用自己的优雅方式?

[英]Elegant way for a singleton to reference itself in JS/coffeescript?

I'm creating a module consisting of a singleton designed to store data: 我正在创建一个由用于存储数据的单例组成的模块:

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

I want select to contain methods for accessing attributes inside the selected sub-object. 我想选择包含用于访问selected子对象内属性的方法。 However, unlike a closure, I can't store this inside a named variable, and I can't access context from within context.select as this will refer to context.select 然而,不同于封闭,我不能存储this名为变量里面,我无法访问context从内部context.select因为this将涉及context.select

How can I establish a reference to the parent/root object for use within sub-objects? 如何建立对父/根对象的引用以在子对象中使用?

I encourage you to create classes with no namespaces for improved readability. 我鼓励您创建没有名称空间的类,以提高可读性。 Here you are, thou: 您在这里,您:

# 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 = []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM