maxedison
maxedison

Reputation: 17553

Backbone model save() method not doing anything

I'm using Backbone with Rails and trying to save a new model to the server. However, calling .save() on the model doesn't seem to be doing anything. Looking at the "Network" tab in Chrome, I don't see any request being made. Here's my code:

Model

class MyApp.Models.Chain extends Backbone.Model
    defaults:
        steps: []
        id: null

    urlRoot: '/chains'

    validate: (attrs) ->
        if $.trim(attrs.steps[@step_number - 1]) == ''
            return "Step can't be blank."

View

class MyApp.Views.ChainsNew extends Backbone.View

    # @template is defined by a conditional inside render()
    initialize: ->
        @is_saving = false

    events:
        'click #btn-go': 'add_step'
        'click #btn-done': 'save'

    render: (step_number) ->
        @model.step_number = step_number

        @template = if @model.step_number is 1 then JST['chains/new'] else JST['chains/step']
        $(@el).html(@template({previous_step_text: @model.get('steps')[step_number - 2]}))

        @

    add_step: ->
        #divide array into arrays of steps before and after step being edited
        steps = @model.get('steps')
        array1 = steps.slice(0, @step_number - 1)
        array2 = steps.slice(@step_number)
        array1.push(@$el.find('textarea').val())
        newArray = array2.concat(array1)

        if [email protected]({steps: newArray}, {validate: true})
            alert(@model.validationError)
            false
        else
            true #need to a return a value for the `save` method

    save: ->
        @is_saving = true
        if @add_step
            @model.save(null, {
                success: ->
                    console.log(arguments)

                error: ->
                    console.log(arguments)
            })

I know that @model.save is being called because I have logged a message right before it to the console (in other words if @add_step is true).

Upvotes: 0

Views: 67

Answers (1)

David Sulc
David Sulc

Reputation: 25994

Most likely, your model is failing validation, which makes save return false and make no API call. Try with

class MyApp.Models.Chain extends Backbone.Model
    defaults:
        steps: []
        id: null

    urlRoot: '/chains'

    validate: (attrs) ->
        if $.trim(attrs.steps[@step_number - 1]) == ''
            console.log "Houston, we have a problem"
            return "Step can't be blank."

If you see a message in the console, there's the issue. You can also try to completely comment the validatefunction, and an API call should be made in all circumstances.

Upvotes: 2

Related Questions