how to use Backbone.js, but in the NO-RESTful way?

前端 未结 3 1760
野趣味
野趣味 2021-02-01 07:02

I\'m now a front-end developer, and I have a project which is fine to use BackboneJS, and the server-side is written by others. Is there anyone who can tell me how to override

3条回答
  •  渐次进展
    2021-02-01 07:42

    Backbone uses Backbone.sync to manage all communication with the server. There are two important things about sync for you; first of all, it looks like this:

    The method signature of Backbone.sync is sync(method, model, [options])

    • method – the CRUD method ("create", "read", "update", or "delete")
    • model – the model to be saved (or collection to be read)
    • options – success and error callbacks, and all other jQuery request options

    and the second is that you can override sync on a per-model and per-collection basis. So you can add your own sync implementation to your model:

    var M = Backbone.Model.extend({
        sync: function(method, model, options) {
            //...
        },
        //...
    });
    

    If you look at method you can decide which URL to use and whether you're doing a GET, POST, ... request. The model will tell you what data to send to the server. You'll want to merge options into the $.ajax options you want to use. Have a look at the standard implementation of Backbone.sync, it is pretty straight forward and should show you what you need to do: just replace the URL handling and drop some of the features you don't care about (such as emulateHTTP and emulateJSON).

提交回复
热议问题