0

我想我忘记了这个术语,所以欢迎编辑标题。我想做的是为我的$scope对象分配多个函数,如下所示:

    $scope.
      widgetDropped = (event, ui) ->
        (console.log "widget dropped")
      dragCallback = (event, ui) ->     # fails
        console.log("started drag")     # fails

所以前 3 行编译正常,但添加最后 2 行会导致编译失败。有点混乱线延续,没​​有运气。是否可以在咖啡脚本中进行这种多行对象分配?

4

2 回答 2

1

我想你正在寻找这样的东西:

$scope =
  widgetDropped : (event, ui) ->
    console.log "widget dropped"
  dragCallback : (event, ui) ->
    console.log "started drag"

之后,您可以调用您的函数:

$scope.widgetDropped()  # logs "widget dropped"
$scope.dragCallback()   # logs "started drag"

这是运行示例

如果您喜欢它,您可以添加大括号以清楚起见:

$scope = {
  widgetDropped : (event, ui) ->
    console.log "widget dropped"
  dragCallback : (event, ui) ->
    console.log "started drag"
}
于 2013-06-29T12:56:33.440 回答
0

If you're trying to extend (i.e. set multiple properties at once) $scope like this:

$scope.widgetDropped = (event, ui) -> console.log "widget dropped"
$scope.dragCallback  = (event, ui) -> console.log("started drag")

then you're out of luck, there's nothing native to CoffeeScript for that. Various libraries offer functions for that though, Underscore/Lodash for example:

_($scope).extend(
    widgetDropped: (event, ui) -> console.log "widget dropped"
    dragCallback:  (event, ui) -> console.log("started drag")
)

jQuery has one too.

There are various forms of destructured assignment that go the other way:

o = { where: 'is', pancakes: 'house?' }
{ pancakes } = o
# pancakes is now 'house?'

but no native merging techniques.

于 2013-06-28T17:20:48.530 回答