Reputation: 7156
I am experimenting with a Rails-BackboneJS stack, and I see in some demo projects the use of Backbone.sync.rails, e.g. in this style: https://github.com/codebrew/backbone-rails/blob/master/vendor/assets/javascripts/backbone_rails_sync.js
As far as I understand this overrides the Sync functions for Backbone Models and Collections. In my case however, I get a bit strange effects (unexpected nesting in models, empty collections).
So, I am asking myself, what is the purpose of the Rails sync helpers? What is important to consider when (not) using these helpers?
Thanks!
Upvotes: 3
Views: 293
Reputation: 35812
Sync is essentially Backbone's general purpose hook for all lower-level data-handling customization. They sort of say as much in the docs for sync:
Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses jQuery.ajax to make a RESTful JSON request and returns a jqXHR. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.
In the case of the Rails sync helper, the author didn't even go so far as to change the basic nature of the sync (eg. to Local Storage). Instead, his sync still "uses jQuery.ajax to make a JSON request and returns a jqXHR", but it:
You can see #1 here:
beforeSend: function( xhr ) {
if (!options.noCSRF) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
}
model.trigger('sync:start');
}
and #2 here:
if(model.paramRoot) {
data[model.paramRoot] = model.toJSON();
} else {
data = model.toJSON();
}
I can't tell exactly why you're getting
strange effects (unexpected nesting in models, empty collections)
but personally I'd recommend just writing your own Backbone.sync
. As you can see, there's not much to implementing it's features, and by making your own custom one you inherently understand how it works (which is good since it's so key for your app).
Or, you could avoid the whole Backbone.sync
override approach entirely. Instead, you could use other mechanisms, such as jQuery .ajaxSend()
to handle #1 or your own custom Model.toJSON
override for #2.
Upvotes: 2