Reputation: 277
I have a confusion -
If I am implementing websockets (sockjs)
on top of Backbone
and Marionette
, then, in my opinion, it should only require a change in Backbone.ajax
function so that socket.emit
and socket.on
are supported in place of model.save (or collection.save)
and model.fetch (or collection.fetch)
.
However, when I did some research and I found that this was not the case. I came across -
1. Derick Bailey's article:
https://lostechies.com/derickbailey/2012/04/19/decoupling-backbone-apps-from-websockets/
which doesn't even talk about changing Backbone.ajax
or Backbone.sync
, instead it suggests event aggregation - which is a part of the solution of using websockets but misses the whole point of syncing models and collections. Ok, it does talk about backbone.iobind
but only mentions it as an "alternative" approach to event aggregation (however, this is only my reading of the article, I might have missed something!).
2. And Christopher Keefer's article:
http://artandlogic.com/2014/06/websockets-for-backbone/
It does exactly what I want (on socket.io) but it does the job by changing parts of Backbone.sync
except Backbone.ajax
!
My question is whether Backbone can work for sockjs just by changing its Backbone.ajax
function?
Upvotes: 0
Views: 296
Reputation: 43156
If you want to change your persistence methods, you should override Backbone.sync
You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.
(emphasis mine)
Backbone.sync
is your gateway to persistence layer. By default this is handled using AJAX, and in most cases uses jQuery AJAX.
Backbone.ajax
If you want to use a custom AJAX function, or your endpoint doesn't support the jQuery.ajax API and you need to tweak things, you can do so by setting Backbone.ajax.
(emphasis mine)
Backbone.ajax
is just a proxy to jQuery AJAX:
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
}
The docs clearly says when you would want to override Backbone.ajax
. Another unrealistic example would be when you're using another DOM manipulation library in place of jQuery which doesn't have built in AJAX support exposed using an ajax
method.
Backbone.sync
method contains code that assumes you're using AJAX (it manipulates an xhr
object). That's what you should override.
Using ajax
method to do something that isn't ajax doesn't even make sense.
Upvotes: 1