Zhen
Zhen

Reputation: 12431

How to check for success event after executing a save() on a model

I am using the following code to save additional properties to a model (answer model in this case)

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")

I want to execute a set of commands only when the save is executed successfully. I tried the code above but it is not working (although I checked that the data was indeed saved)

Please advise on how I can modify the code to check for the success event

Upvotes: 0

Views: 419

Answers (1)

mu is too short
mu is too short

Reputation: 434685

You're using save incorrectly. Backbone's save takes separate attributes and options arguments:

save model.save([attributes], [options])
[...]
save accepts success and error callbacks in the options hash,

but you're only passing one hash. You need to call it like this:

@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")

or perhaps like this if you really hate braces:

@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")

Upvotes: 1

Related Questions