Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Backbone.sync with nothing, not even localStorage?

How do you replace Backbone.sync to do nothing? My app has a "Submit" button which will do the AJAX POST for me, so I don't want to use the auto-magic default behavior that Backbone.sync provides.

I also don't want to use Backbone LocalStorage adapter as I am trying to make this site compatible with IE6 and 7.

That being said, I pretty much just want Backbone to do nothing except retain the records in the JS memory (similar to Spine.js). Is this even possible?

like image 940
kidcapital Avatar asked Oct 13 '11 04:10

kidcapital


2 Answers

The easiest and probably best way to do this is not to replace Backbone.Sync, but simply to ignore it. Here are the methods you don't want to call:

Collections:

  • fetch
  • create

Models:

  • fetch
  • save
  • destroy

If you avoid calling any of these methods, you will effectively ignore Backbone.Sync and be able to write your own code to do your AJAX calls.

I wrote a lot of Backbone code without ever having a server call involved, when I started. There are no rules to say that you have to use all of Backbone's capabilities. In fact, I would say the opposite is true. Backbone is written in such a modular manner with each area of functionality and specialization roped off so well, that you should only use what you actually need.

Create your models in memory, call set and get on them to store data. Stuff them into collections with add and remove them as needed. Pass your models and collections to your views and render them out to the HTML DOM. Just avoid calling the methods I listed above and you won't have to worry about Backbone.Sync.

like image 93
Derick Bailey Avatar answered Oct 23 '22 19:10

Derick Bailey


I once made this gist as part of a tutorial on Backbone.js. It fakes Backbone.sync by only writing to a log, but to give it a semblance of realism it also copies the .cid attribute of a model to it's .id attribute to make the models appear to be synced. Beware of various unwanted consequences of using that technique in production! But we're all consenting adults here, right?

Here's the same idea without the logging:

Backbone.sync = function(method, model, succeeded) {
    if(typeof model.cid != 'undefined') {
        // It's a freshly made model
        var cid = model.cid;
        // ..fake that it's .cid turns into a "real" .id:
        model.unset('cid').set({id:cid}, {silent:true});
    }
    // Oh yes, it all went sooo well ;-)
    succeeded(model);
};
like image 1
Jacob Oscarson Avatar answered Oct 23 '22 18:10

Jacob Oscarson