Javascript

Overriding Backbone.sync for local use

If you’re using Backbone to develop the front end in a local application you’ll have to override the Backbone.sync functionality to replace the REST functionality normally used by the library. Using Backbone in a local environment to store data, whether to store data in a file on the hard drive or using a local DB, is a bit different from its normal usage. The REST functionality has to be replaced with a file write or some other data storage code. The code below works for me:

Backbone.sync = function(method, model, options) {
    if (method === "create"){
        let attrs = model.changed;
        if(Object.keys(attrs).length>0){
            console.log("Update a record.");
        }else{
            console.log("Create a record.");
        }
    }
    if(method === "read"){
        if(model.length === 0){
            console.log("Pull the entire collection of records.");
        }else{
            console.log("Pull a single record.");
        }
    }
    if(method === "delete"){
        console.log("Delete this record and return nothing.");
    }
    if(method === "update"){
        console.log("This update functionality never runs.");
    }
};
Standard

Leave a comment