我有一个Backbone.js模型,当用户点击模型视图中的链接时,我正试图销毁它.视图是这样的(伪代码,因为它是在CoffeeScript中实现的,可以在问题的底部找到).
var window.ListingSaveView = Backbone.View.extend({
events: {
'click a.delete': 'onDestroy'
},
onDestroy: function(event){
event.preventDefault();
this.model.destroy({
success: function(model, response){
console.log "Success";
},
error: function(model, response){
console.log "Error";
}
});
}
});
当我在浏览器中单击delete
链接时,我总是会将Error
记录到控制台,即使我的服务器记录了相关数据库记录的成功销毁并返回200响应.当我刷新页面(导致集合从数据库重新呈现)时,我删除的模型将消失.
有趣的是,当我在错误回调中记录response
时,它的状态码200
表示成功,但它也报告statusText: "parseerror"
,不管这意味着什么.我的服务器日志(log)中没有错误.
我做错了什么?
这是来自服务器的响应:
Object
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
isRejected: function () {
isResolved: function () {
overrideMimeType: function ( type ) {
pipe: function ( fnDone, fnFail ) {
promise: function ( obj ) {
readyState: 4
responseText: " "
setRequestHeader: function ( name, value ) {
status: 200
statusCode: function ( map ) {
statusText: "parsererror"
success: function () {
then: function ( doneCallbacks, failCallbacks ) {
__proto__: Object
下面是destroy与(Ruby on Rails)交互的服务器操作
# DELETE /team/listing_saves/1.json
def destroy
@save = current_user.team.listing_saves.find(params[:id])
@save.destroy
respond_to do |format|
format.json { head :ok }
end
end
下面是主干视图的实际CoffeeScript实现,供喜欢它的人使用:
class MoveOutOrg.Views.ListingSaveView extends Backbone.View
tagName: 'li'
className: 'listing_save'
template: JST['backbone/templates/listing_save']
events:
'click a.delete_saved': 'onDestroy'
initialize: ->
@model.bind 'change', this.render
render: =>
renderedContent = @template(@model.toJSON())
$(@el).html(renderedContent)
this
onDestroy: (event) ->
event.preventDefault() # stop the hash being added to the URL
console.log "Listing Destroyed"
@model.destroy
success: (model, response)->
console.log "Success"
console.log model
console.log response
error: (model, response) ->
console.log "Error"
console.log model # this is the ListingSave model
console.log response