Hien
Hien

Reputation: 165

backbone sync callback always use error

I am having a hard time figuring out how to get the callback to work correctly when using Backbone sync. I am looking at my return packets and the response code is 200 which is no error, yet the alert("fail") statement gets called. I am requesting a response from a java servlet. Any idea guys? Thanks

Backbone.sync("read", this.model, {
  url : "some url",
    success: function(model, response) {
      alert(response);
    },
    error: function(model, response) {
      alert("fail");
    }
});

Upvotes: 1

Views: 2071

Answers (2)

Vlad
Vlad

Reputation: 844

Make sure that your servlet returns a JSON object, even if it's empty. This fixed the issue in my case.

Upvotes: 1

inf3rno
inf3rno

Reputation: 26129

I don't understand what you are doing...

Use this methods instead of sync:

model.fetch();
model.save();
model.destroy();

They will call sync, and they work perfectly.

I don't think it's necessary to override the original sync, it is good enough. I created a mock sync for an example application, this is how it works:

var User = Backbone.Model.extend({
    notAllowedEmailHost: "gmail.com",
    sync: function (method, model, options) {
        if (method == "read" || method == "delete")
            throw new Error("Example is not prepared for these methods.");
        var email = model.get("email");
        var status = 201;
        if (email.indexOf(this.notAllowedEmailHost) != -1)
            status = 400;
        else if (method == "update")
            status = 500;
        options.xhr = {
            status: status
        };
        if (status >= 400)
            options.error(options.xhr);
        else
            options.success({
                id: 1
            });
    }
});

The methods above create wrapper functions around your callbacks, and in sync those wrappers are called with the result. So the callback in sync is not the callback you give by the call of fetch, save or destroy functions...

Upvotes: 2

Related Questions