Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom "sync" method in Backbone.js

Creating a custom sync() method in backbone.

I would like to do this the "right" and interfere with Backbone's normal functions as little as possible.

This is the code that I have so far:

var CustomSyncModel = Backbone.Model.extend({
    sync:function(method, model, options){
        var params = {
            type: 'POST'
            url: model.url(),
            error: function(jqXHR, textStatus, errorThrown){
                alert('error');
            },
            success: function(data, textStatus, jqXHR){
                model.parse(data);
            }
        };
        // Got this from line 1359 in Backbone.js developement library
        //     version 0.9.2:
        $.ajax(_.extend(params, options));
    }
 });

The issue that I am having is that the line: $.ajax(_.extend(params, options)); seems to be overwriting the custom success and error functions that I created. But I'm also concerned about interfering with any custom callbacks or other functionality that may have been specified elsewhere in the application that is using this model.

What is the "correct" way to go about overriding the Backbone's sync() method?

Thanks!

like image 302
Chris Dutrow Avatar asked Aug 19 '12 18:08

Chris Dutrow


1 Answers

If you look at Model#fetch you'll see the usual approach that Backbone uses:

fetch: function(options) {
  //...
  var success = options.success;
  options.success = function(resp, status, xhr) {
    if (!model.set(model.parse(resp, xhr), options)) return false;
    if (success) success(model, resp);
  };
  //...
}

So Backbone just replaces the function with a new one that calls the original. In your case, you'd have something like this:

// We don't own options so we shouldn't modify it,
// but we can do whatever we want to a clone.
options = _(options).clone()

// Replace options.error with a wrapper.
var error = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
    alert('error');
    if(error)
        error(jqXHR, textStatus, errorThrown);
};

// Replace options.success with a wrapper.
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
    model.parse(data);
    if(success)
        success(data, textStatus, jqXHR);
};

// We don't need error or success in here anymore.
var params = {
    type: 'POST',
    url:   model.url() 
};
$.ajax(_.extend(params, options));

BTW, your model.parse(data); in your success handler probably doesn't do anything useful, parse should just be a simple filter so you'd want to do something (such as a model.set call) with the model.parse(data) return value.

like image 135
mu is too short Avatar answered Sep 24 '22 06:09

mu is too short