开发者

Backbone.js cancel Model.destroy

When I call Model.destroy, it sends the proper requests to the server. However, I handle er开发者_C百科rors not so RESTful, I return a JSON with some appropriate information instead of throwing a http exception.

Now I want to be able to prevent the deletion of the model in the callbacks. For ex;

window.UserView = Backbone.View.extend({
    //Other stuff here.
    clearSuccess: function (model, response) {
        if (!response.Exception) {
            $(this.el).fadeOut('fast', function() {
                $(this).remove();
            });
        }
        else {
            //Can I cancel the destroy here?
        }
    },
    clearFailed: function (model, response) {
        alert("failed");
    }
});

These are the 2 callbacks that I sent to the model's success and error parameter on the destroy method. So where my comment is, I'd like to tell Backbone.js "nevermind, server said I cant delete, so keep the model". How do I do this?


You have control of the content body with ASP.net MVC. Just set the Response.StatusCode property to the value you want to use, then return a JSON response or a Content response, or whatever.

Response.StatusCode = (int)HttpStatusCode.Conflict;
return Json( errorMessage );

Works just fine.


The simplest thing is probably to return both a non-success HTTP status code (400-599) and a response body with a JSON document with application-level error details. See this thread for more on the HTTP status:

Using HTTP status codes to reflect success/failure of Web service request?

If you do this, backbone should automatically know that a failure status means the destroy did not succeed on the server, and I think it will do the right thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜