【问题标题】:what does ":" mean in this case in coffee script?在这种情况下,咖啡脚本中的“:”是什么意思?
【发布时间】:2015-05-11 13:46:36
【问题描述】:

我是咖啡脚本的新手。当我查看此文档时https://atom.io/docs/api/v0.198.0/CommandRegistry#instance-add 我看到这样的代码段,

atom.commands.add 'atom-text-editor',
  'user:insert-date': (event) ->
    editor = @getModel()
    editor.insertText(new Date().toLocaleString())

虽然函数签名看起来,

::add(target, commandName, callback)

那么在代码段中,第二行的:是什么意思呢?我的理解是签名中: 之前的'user:insert-date' 是commandName: 之后的东西是“回调”。那么: 是像, 这样的参数分隔符吗?咖啡脚本文档http://coffeescript.org

中没有发现这个介绍

【问题讨论】:

    标签: coffeescript


    【解决方案1】:

    那个冒号只是对象字面量的一部分。在没有歧义的情况下,CoffeeScript 中对象字面量周围的大括号是可选的。如果我们添加可选的大括号,我们会得到看起来更像 JavaScript 的东西:

    atom.commands.add 'atom-text-editor', {
      'user:insert-date': (event) ->
        #...
    }
    

    所以atom.commands.add 被调用时带有两个参数。第一个是字符串'atom-text-editor',第二个是一个带有一个键('user:insert-date')的对象,它的值是一个接受单个参数的匿名函数。

    【讨论】:

    • 这对我很有帮助。谢谢。
    【解决方案2】:

    附加 mu 的答案太短(用户绝对正确,第二个参数 commandName 可以是没有显式大括号 {} 的对象)

    Atom 的源代码: https://github.com/atom/atom/blob/v0.198.0/src/command-registry.coffee#L81

    add: (target, commandName, callback) ->
    if typeof commandName is 'object'
      commands = commandName
      disposable = new CompositeDisposable
      for commandName, callback of commands
        disposable.add @add(target, commandName, callback)
      return disposable
    

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 1970-01-01
      • 2020-04-04
      • 2017-03-28
      • 2016-08-26
      • 2014-10-27
      • 2019-10-15
      • 2020-11-03
      • 1970-01-01
      相关资源
      最近更新 更多