Permalink
Browse files

Merge pull request #25 from pollensoft/master

Default to the original Backbone sync method when no localStorage is available
  • Loading branch information...
2 parents 74c7fad + 8cafed1 commit 834375335329faffeedb0f086042dd8afeafe09a @jeromegn committed Mar 26, 2012
Showing with 33 additions and 5 deletions.
  1. +16 −4 backbone.localStorage.js
  2. +17 −1 tests/test.js
View
@@ -82,6 +82,7 @@ _.extend(Backbone.LocalStorage.prototype, {
// *localStorage* property, which should be an instance of `Store`.
// window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead
Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options, error) {
+ var store = model.localStorage || model.collection.localStorage;
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
@@ -92,7 +93,6 @@ Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(m
}
var resp;
- var store = model.localStorage || model.collection.localStorage;
switch (method) {
case "read": resp = model.id != undefined ? store.find(model) : store.findAll(); break;
@@ -108,9 +108,21 @@ Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(m
}
};
-// Override 'Backbone.sync' to default to localSync,
-// the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
Backbone.ajaxSync = Backbone.sync;
-Backbone.sync = Backbone.LocalStorage.sync;
+
+Backbone.getSyncMethod = function(model) {
+ if(model.localStorage || (model.collection && model.collection.localStorage))
+ {
+ return Backbone.localSync;
+ }
+
+ return Backbone.ajaxSync;
+};
+
+// Override 'Backbone.sync' to default to localSync,
+// the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
+Backbone.sync = function(method, model, options, error) {
+ Backbone.getSyncMethod(model).apply(this, [method, model, options, error]);
+};
})();
View
@@ -142,5 +142,21 @@ $(document).ready(function() {
book.destroy()
equals(Book.prototype.localStorage.findAll().length, 0, 'book removed');
});
-
+
+ test("Book should use local sync", function()
+ {
+ var method = Backbone.getSyncMethod(book);
+ equals(method, Backbone.localSync);
+ });
+
+ var MyRemoteModel = Backbone.Model.extend();
+
+ var remoteModel = new MyRemoteModel();
+
+ test("remoteModel should use ajax sync", function()
+ {
+ var method = Backbone.getSyncMethod(remoteModel);
+ equals(method, Backbone.ajaxSync);
+ });
+
});

0 comments on commit 8343753

Please sign in to comment.