【问题标题】:How to check for success event after executing a save() on a model如何在模型上执行 save() 后检查成功事件
【发布时间】:2012-02-27 08:21:01
【问题描述】:

我正在使用以下代码将其他属性保存到模型(在本例中为答案模型)

selectMedia: =>
  # Post media to server
  @options.answer.id = @options.answer.get('_id')
  @options.answer.url = "/v1/answers/#{@options.answer.get('_id')}"

  @options.answer.save
    youtube_id: @options.media.get('vid')
    success: (result) =>

      $('.modal').html('')
      $('.modal').modal('toggle')
      @options.question_view.remove()
      @options.question_view.render()
    error: ->
      console.log("error")

我只想在保存成功时执行一组命令。 我尝试了上面的代码,但它不起作用(虽然我检查了数据确实保存了)

请告知我如何修改代码以检查成功事件

【问题讨论】:

  • 这看起来有点像骨干。你在使用主干吗?如果是这样,请将其添加到标签中。

标签: javascript ajax backbone.js coffeescript


【解决方案1】:

您错误地使用了save。骨干的save takes separate attributes and options arguments:

保存 model.save([attributes], [options])
[...]
save 接受选项哈希中的成功和错误回调,

但你只传递了一个哈希值。你需要这样称呼它:

@options.answer.save { youtube_id: @options.media.get('vid') }
  success: (result) =>
    $('.modal').html('')
    $('.modal').modal('toggle')
    @options.question_view.remove()
    @options.question_view.render()
  error: ->
    console.log("error")

如果你真的讨厌大括号,也许可以这样:

@options.answer.save 'youtube_id', @options.media.get('vid')
  success: (result) =>
    $('.modal').html('')
    $('.modal').modal('toggle')
    @options.question_view.remove()
    @options.question_view.render()
  error: ->
    console.log("error")

【讨论】:

  • 我一直在尝试遵循这一点,但是每当我在函数之后添加 -> 时,它都不会被调用。如果我把 -> 从他们身上拿走,尽管成功和错误函数都被调用了。你知道这是服务器问题还是客户端问题?正如我所料,返回 500 内部错误...
  • @TomHammond:如果不确切地看到你在做什么,很难说发生了什么。 CoffeeScript 松散的语法可能是一个诅咒。
  • 将此保存为我反对 CoffeeScript 的论据。你的答案的两个版本都有奇怪的语法(显然不是你的错)。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
相关资源
最近更新 更多