我正在使用Backbone和Rails并尝试将新模型保存到服务器。但是,在模型上调用.save()
似乎没有做任何事情。查看Chrome中的“网络”标签,我看不到任何要求。这是我的代码:
模型
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."
查看
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 !@model.set({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)
})
我知道正在调用@model.save
,因为我已经在它之前将一条消息记录到控制台(换句话说,if @add_step
为真)。
答案 0 :(得分:2)
最有可能的是,您的模型验证失败,导致save
返回false并且不进行API调用。试试
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."
如果您在控制台中看到一条消息,则表明存在问题。您还可以尝试对validate
函数进行完全注释,并且应该在所有情况下都进行API调用。