Jon Wells
Jon Wells

Reputation: 4259

Overriding Backbone Sync to use diiferent calls for fetch/save/destroy

The reason I'm late to the backbone party is because I'm worried it wont play nicely with my existing webservice. I have even got to the point where I'm using my own version of backbones controllers and models, but its fruitless to just write my own, (certainly) worse, implementation.

I am using a Asp.net web service, so, on the assumption we are updating a user model I use the following three calls:

myservice/deleteUser.aspx?id=1
myService/getUser.aspx?id=1
myService/setUser.aspx? //post model

I don't see how this works with backbones sync ? I assume I'd have to overwrite fetch/save and destroy?

I'd be really grateful for some good examples. I have read around the subject, including the annotated source, but I'm struggling for the "ah ha" moment.

Upvotes: 3

Views: 5665

Answers (1)

nikoshr
nikoshr

Reputation: 33344

You can provide your collections or models with a custom sync function which will be called instead of Backbone.sync when you fetch/update/destroy an element. You can then tailor the options to emit a request matching your server setup. For example,

var M = Backbone.Model.extend({

    sync: function(method, model, options) {
        options || (options = {});

       // passing options.url will override 
       // the default construction of the url in Backbone.sync

        switch (method) {
            case "read":
                options.url = "/myservice/getUser.aspx?id="+model.get("id");
                break;
            case "delete":
                options.url = "/myservice/deleteUser.aspx?id="+model.get("id");
                break;
            case "update":
                options.url = "/myService/setUser.aspx";
                break;
        }

        if (options.url)
            return Backbone.sync(method, model, options);
    }

});

var c = new M({id: 1});
c.fetch();
c.save();
c.destroy();

And a Fiddle simulating these calls http://jsfiddle.net/nikoshr/4ArmM/

If using PUT and DELETE as HTTP verbs bothers you, you can force a POST by adding Backbone.emulateHTTP = true; See http://jsfiddle.net/nikoshr/4ArmM/1/ for a revised version.

Upvotes: 13

Related Questions