我想通过 coffeescript 在没有 return 的情况下回调方法

I want to callback method without return by coffeescript

我写了下面的代码。

initialize : ->
@model.apiForecast = new ApiForecastModel(
  model: @model.get('apiForecast')
)
@model.forecast = new ForecastModel(
  model: @model.get('forecast')
)
cookie = Cookie()
forecastCall = this.model.forecast.fetch(
  data:
    token: cookie['Authorization']
  headers:
    Authorization: cookie['Authorization']
  success: ->
    console.log('Success Forecast')
  error: (e) ->
    console.log('Service request failure: ' + e)
)

$.when( forecastCall )
.done( () -> (
    @getApiForecast()
    return
  ).bind(@)
  return
)
return

但是后来我得到了这个错误。

error: unexpected indentation

实际上,我想编译成这样的 ajax 代码。

$.when( forecastCall ).done(
  function () {
    this.getApiForecast();
  }.bind(this)
);

你有什么决心吗?

您的 bind 调用工作的括号位置错误。您希望将整个匿名函数包裹在括号中,而不仅仅是函数的主体:

$.when( forecastCall )
.done( ( ->
    @getApiForecast()
    return
).bind(@))

或更好(或至少噪音较小),使用 => 函数并让 CoffeeScript 负责绑定:

$.when( forecastCall ).done( =>
  @getApiForecast()
  return
)

我假设你问题中的所有代码实际上都在 initialize