Giter Club home page Giter Club logo

backbone.localstorage's People

Contributors

4vanger avatar andreypopp avatar basicallydan avatar dremora avatar dwt avatar dy avatar eastridge avatar eush77 avatar fluxusfrequency avatar jeromegn avatar joemcelroy avatar juhovh avatar kmiyashiro avatar marcelklehr avatar marlun78 avatar nbergseng avatar nekman avatar paulmillr avatar rbu avatar renfredxh avatar richardchen331 avatar rsskga avatar ryan-roemer avatar ryangreenberg avatar schickling avatar scott-w avatar snappedtogrid avatar ssorallen avatar toddbranch avatar uzikilon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backbone.localstorage's Issues

DOMException not defined in IE8

Source:

} catch(error) {
    if (error.code === DOMException.QUOTA_EXCEEDED_ERR && store._storageSize() === 0)
      errorMessage = "Private browsing is unsupported";
    else
      errorMessage = error.message;
  }

The DOMException object is used, which is not defined for IE8 afaik.

LocalStorage with a simple Model Error

Hi.
I'm trying to use your plugin pretty regularly:

var MediaSearch = Backbone.Model.extend({
    defaults: {
        query: 'pink floyd'
    },

    localStorage: new Backbone.LocalStorage('MediaSearchModel')
});

var search = new MediaSearch();
search.save('query', 'live shows');

After I refresh the page, and create a new instance of MediaSearch, I use fetch:

var MediaSearch = Backbone.Model.extend({
    defaults: {
        query: 'pink floyd'
    },

    localStorage: new Backbone.LocalStorage('MediaSearchModel')
});
var search = new MediaSearch();
search.fetch();

I expect search to have query = 'live shows' - but it doesn't.
Is this a bug OR it should work differently?

Thanks.

"model.set(model.idAttribute, guid())" fires second "change" event

When I try the first "save" for my model the "set" call inside the "create" function fires second "change" event on the model:

if (!model.id) {
model.id = guid();
model.set(model.idAttribute, model.id);
}

I think it's a bug but if it's necessary please explain how can I deal with this issue to avoid double call of "change" callback?

Allowing localStorage on old devices

The old devices are not compatible with localStorage, I found a code that adds support to these devices as the BlackBerry, IE etc, it works with cache (with size and expiration limits),

mozilla https://developer.mozilla.org/en/DOM/Storage#localStorage

I hope that is helpful for your plug-in

if (!window.localStorage) {
window.localStorage = {
prefix:'localStorage',
getItem: function (ssKey) {
var sKey=ssKey+this.prefix;
if (!sKey || !this.hasOwnProperty(ssKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.
;\s
)" + escape(sKey).replace(/[-.+*]/g, "$&") + "\s
=\s_((?:^;)[^;]?)."), "$1"));
},
key: function (nKeyId) { return unescape(document.cookie.replace(/\s_=(?:.(?!;))$/, "").split(/\s=(?:^;)[^;]?;\s/)[nKeyId]); },
setItem: function (ssKey, sValue) {
var sKey=ssKey+this._prefix;
if(!sKey) { return; }
var sExpDate = new Date();
sExpDate.setDate(sExpDate.getDate() + 30);
document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=" + sExpDate.toGMTString() + "; path=/";
this.length = document.cookie.match(/_localStorage=/g).length;
},
length: 0,
removeItem: function (ssKey) {
var sKey=ssKey+this._prefix;
if (!sKey || !this.hasOwnProperty(ssKey)) { return; }
var sExpDate = new Date();
sExpDate.setDate(sExpDate.getDate() - 1);
document.cookie = escape(sKey) + "=false; expires=" + sExpDate.toGMTString() + "; path=/";
this.length--;
},
hasOwnProperty: function (ssKey) { var sKey=ssKey+this.prefix; return (new RegExp("(?:^|;\s)" + escape(sKey).replace(/[-.+]/g, "$&") + "\s=")).test(document.cookie); }
};
window.localStorage.length = (document.cookie.match(/_localStorage=/g) || window.localStorage).length;
window.localStorage.clear=function(){
window.localStorage.length = (document.cookie.match(/_localStorage=/g) || window.localStorage).length;
var allCookies = document.cookie.split(";");
var cookies=new Array();
for(var i=0;i<=allCookies.length -1 ;i++){
var nameCookie=allCookies[i].split("=")[0];
if(nameCookie.match(/_localStorage/g)){
window.localStorage.removeItem(nameCookie.replace('_localStorage','').replace(' ',''));
}
}
window.localStorage.length = (document.cookie.match(/_localStorage=/g) || window.localStorage).length;
}
}

Best regards

localStorage in an iFrame on Chrome

put this markup in an HTML file and open it using Chrome (any version):

<iframe width="1200" height="1000" src="http://todomvc.com/architecture-examples/backbone/"></iframe>

You get this error on page load:

Uncaught Error: SECURITY_ERR: DOM Exception 18

does anyone know a workaround?

Setting {wait: true} causes models to be created incorrectly

n = notebooks.create({title: 'oh hai'}, {wait: true})
n
// n is a Notebook
n.attributes
// returns Notebook
n = notebooks.create({title: 'oh hai'})
n.attributes
// returns Object

In the former case, the model cannot be saved as it causes a stack overflow. The attributes are the model object itself rather than a simple object containing attributes.

Use of GUID's

The size of models stored in local storage rapidly increases when creating many models - would it be better to remove the GUID function and maintain an incremental counter when assigning new ID's?

Release as NPM package

It would be nice to have this package in NPM registry, especially for apps which rely on browserify.

Unable to .save() a model which is part of a collection

Hi,

I'm using Backbone 0.9.10 and Backbone LocalStorage 1.1.0 and I'm having some difficulties.

I have a very simple model, called Point. Here's the code:

f1.models.Point = Backbone.Model.extend({
    localStorage: new Backbone.LocalStorage("Point"),

    initialize: function () {
        f1.log('Point::initialize');
    }
});

I also have a collection which is just a collection of Point models. Again, here is the code:

f1.collections.PointList = Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage("PointList"),

    initialize: function () {
        f1.log('PointList::initialize');
    }
});

In one of my views I create an empty instance of PointList and then add some points to it using Backbones .add() method on the PointList collection. I then do some event binding as the model attributes are modified client side.

The difficulty I'm having is with trying to save an instance of the Point model which is part of my PointList collection. When I try and call .save() on the Point Model instance nothing happens.

Having traced the code, it gets to line 59 in backbone.localStorage.js which reads:

this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));

Once this line is executed, the application jumps to the catch block as an exception is thrown by JSON.stringify(model). The exception is: TypeError: Converting circular structure to JSON

I believe this occurs because the model contains a reference to the collection it's part of, and that collection contains a reference to all the models it contains. This is of course all standard backbone and I'm doing nothing out of the ordinary here. I might be being crazy here, but shouldn't backbone.localStorage JSONify the models attributes rather than the whole model object?

Please let me know if I'm doing something wrong :)

Thanks!

Setting the id property triggers the change event

I'm not sure if this actually is the wanted behavior or not but model.set(model.idAttribute, model.id); triggers the change event on the model.

In my current use case, this leads to an extra render call of every corresponding controllers, so maybe it would be more efficient to set the id like this model.set(model.idAttribute, model.id, { silent: true }); or even like that model.attributes[model.idAttribute] = model.id;?

Thanks anyway for this great plugin :)

Nested Collections/Models

I'm having problems with this extension and nested collections/models.

Let's say I have a Backbone.Model called "FootballTeam". Inside this model I have a name "FoobarRangers" and a Backbone.Collection "players". The "players" collection contains many instances of "Player", which is a Backbone.Model.

When I do myFootballTeam.save(), the "players" collection is stored as a normal array, and the players in it are stored as normal JavaScript objects. That's good, because it saves space. But when I do: myFootballTeam.fetch(), the "players" collection gets overwritten by the normal JavaScript array, and the players inside it aren't instances of "Player" anymore, they are just JavaScript objects.

For now I have written the "parse" method of FootballTeam to work around this:

parse: function(response) {
        var modifiedResponse = response;
        modifiedResponse.players = new (Backbone.Collection.extend({model: Player}))(response.players);
        return modifiedResponse;
    }

Of course this isn't good because I'd have to do it by hand in many places. Is there a better way?

LocalStorage and 0.9.10 Collection update

At the moment it doesn't appear that the LocalStorage extension does anything with the new collection smart update to save back to localStorage. Is there plans to support it or am I missing something?

Duplicating data?

Hi,

I'm not sure if this is an issue or just I don't know how to use the library properly:

I've created an stack overflow question about this:

http://stackoverflow.com/questions/10549056/duplication-localstorage-data-using-backbone-js-backbone-localstorage-js

Basically I create a model, and when I do the fetch() after the save() I get the data in a different way, stored inside a nested object instead of getting it at attributes property level....

Edit: It looks I'm not the first with this issue:

http://stackoverflow.com/questions/10326690/backbone-js-trouble-persisting-simple-model-to-localstorage
http://stackoverflow.com/questions/7544503/backbone-js-saving-one-model-in-local-storage

Can use collection.get only after fetch()

After saving a model, the collection._byId won't be updated until do a fetch() again. This makes collection.get() to fail.

I investigated a bit and saw that the change event isn't called (the changed object will have nothing). This is necessary to update the _byId.

destroy should return false or something but not the model just deleted

Salut Jรฉrรดme,

dรฉsolรฉ je suis faignant, je te fais la description longue en fr.
La fonction destroy de BB renvoie un XHR ou false, donc quand on utilise destroy, on peut utiliser son retour dans un bรชte if pour savoir si l'appel est passรฉ ou pas.

Hors ta fonction renvoie le model dรฉtruit, soit undefined quand il a bien รฉtรฉ dรฉtruit, ce qui pousse ร  faire le if inverse d'un cas d'utilisation normal ! Du coup quand on passe du localStorage au back end il faut revoir tous les destroy ou trouver un system qui fait une prรฉ condition suivant la config oO

Je te propose de transformer ton return model en if(model) return false else return true, un truc du genre.

short english version, sorry I'm lazzy.

BB destroy return XHR or false, BB.localStorage destroy return the model, kind of defined / true or undefined / false.

So

  • in BB if (destroy) is like destroy send, I can continue my stuff
  • in BB.localStorage if (destroy) is like destroy failed.

Oops BB.localStorage return the opposite of BB destroy.

Fetch a model by id

Hello, why the code below is not issuing an ajax call and instead returns "Record not found"?

var service = new ServiceModel({
    _id: user_id
});
service.fetch(...)

Thanks!

FIX: correctly fetch() content for Backbone.Model Objects

#48

This lib did not correctly fetch()/ 'read'/'GET'
from local storage for Backbone.Model objects after page refresh.

It does work in the tests however because the tests
do not refresh the page and load once again from localStorage.
The tests rely on the in memory version of the object to return the
correct result.

In my personal test this worked for Backbone.Model, but I did
not test Backbone.Collection Objects.

Please test and update the library.

how to remove localStorage completely?

Can you tell me how to remove the localStorage completely if there is no data left in storage?

 test("should be removed completely if no data left", function() {
    library.create(attrs);
    equals(library.first().get('author'), 'Bill Shakespeare', 'author was read');
    library.first().save({ author: 'William Shakespeare' });
    library.fetch();
    equals(library.first().get('author'), 'William Shakespeare', 'verify author update');
    equals(window.localStorage.length, 2, 'two items in store');
    equals(library.length, 1, '1 item in library');
    library.first().destroy(attrs);
    equals(library.length, 0, 'empty library');
    equals(window.localStorage.length, 0, 'zero items in store');
});

if I use this test, I always have one item left in storage and all models are destroyed

One workaround may be:

 window.localStorage.removeItem("LibraryStore");

but I don't like it, because I have to mix up different levels....

thanks

sync'ing models from different pages

Hi,

I have two different pages, each holding an instance of a Model.
When I update some attribute on one page, I cannot sync it in the other page, even with .fetch().

It seems odd, because in Resource tab in Developer Tools (Chrome 20) the data in localStorage has been updated.

// page A
var a = new Item();
a.get("enabled"); // true

// page B
var b = new Item();
b.get("enabled"); // true

// page A
a.save("enabled", false);
a.get("enabled"); // false

// page B
b.fetch();
b.get("enabled"); // should be false, but is true

It however works fine testing on the same page.

Poking here and there I found that reading the localStorage directly reveals the correct behavior:

// page B
JSON.parse(localStorage.getItem("item")).get("enabled"); // false

I don't perfectly understand how object in javascript works,
but maybe the localStorage attribute in the model is cached somewhere and doesn't update?

I tried changing the code so it tries reading localStorage either as a property or as a function (using the getValue function in backbone.js),
and setting it as a function resolves this issue.

Do you think this is worth a patch? Or is there some other easier way to solve this?
Thanks in advance.


This is my first time using both backbone.js and backbone-localstorage.js, so I might be doing something totally wrong. Enlighten me if so.

Collection.each doesn't provide every one?

The first time I call .each, to save the sessions, it gets both. The second time, when destroying, it only gets the first. Any idea why?

  class Session extends Backbone.Model

  class SessionList extends Backbone.Collection
    model: Session
    localStorage: new Store 'sessions'

  window.sessions = new SessionList


  localStorage.removeItem('sessions')
  console.log localStorage.sessions

  sessions.add [
    {x: '1'}
    {x: '2'}
  ]
  console.log localStorage.sessions

  sessions.each (m) ->
    console.log 'saving' + m.get('x') + '  ' + m.get('id')
    m.save()
  console.log localStorage.sessions

  sessions.each (m) ->
    console.log 'kill' + m.get('x') + '  ' + m.get('id')
    m.destroy()
  console.log localStorage.sessions

Console log:

undefined
undefined
saving1  undefined
saving2  undefined
afe778bf-74e1-8013-6cca-ecb8bed794f7,78716671-68cc-de7d-914e-2d64531efc6e
kill1  afe778bf-74e1-8013-6cca-ecb8bed794f7
78716671-68cc-de7d-914e-2d64531efc6e

License?

What license is this code under?

It looks really useful for my project, but I can't use it if it's under some crazy copyleft license. I'm hoping it's MIT licensed like backbone is.

Error on 'localStorage'

Hello, I am getting this error..
Uncaught TypeError: undefined is not a function

On this line (within my collection):
'localStorage: new Backbone.localStorage("SearchQuery")'

Are the docs for this plugin up to date?

Doesn't play well with lodash

Hello i've been working with lodash instead of underscore

the fetch() method on the collection didn't return anything

but with underscore it works fine

localStorage breaks Backbone.js

So I've just downloaded and setup localStorage along with Backbone.js and here's what happening with FireBug:

When using non-minified file:

model.collection is undefined
http://192.168.1.200/assets/js/backbone.localStorage.js
Line 87

Minified version:

d.collection is undefined
http://192.168.1.200/assets/js/backbone.localStorage-min.js
Line 8

help - localstorage in collection

Could you help me ?

I am doing this for add localstorage but in result I can see nathing in the template

var Tweet = Backbone.Model.extend({});

var TweetList = Backbone.Collection.extend({
model: Tweet,
localStorage: new Backbone.LocalStorage("TweetList"),
url: 'http://subealmetro.willyaguirre.me/lineauno.php',
parse: function(response) {
return response;
}
});

var viewTweets = Backbone.View.extend({
tagName: "ul",
className: "badgeslist",
initialize: function(){
this.template = _.template( $("#template").html() );
},
render: function () {
this.$el.html(this.template({tweet: this.model.toJSON()}));
return this;
}
});

var tweetList = new TweetList();

var tweetView = new viewTweets({model: tweetList});

tweetList.bind('reset', function () {   
    $("#tweets").append(tweetView.render().$el);
}); 

tweetList.fetch({reset: true});

Missing brackets?

Missing brackets?
file: backbone.localStorage.js
lines: 73-74
code:
if (!_.include(this.records, model.id.toString()))
this.records.push(model.id.toString()); this.save();

Weird fetch() results

I created a new model and try to persist it with your local storage plugin like this:

Geo = Backbone.Model.extend
  localStorage: new Backbone.LocalStorage('app:geo')

  expires: 1000 * 60 * 20 # 10 minutes

  defaults:
    lat: null
    lng: null

    place: null

    local_phone: null

    updated: 0

It looks like when I call fetch it doesn't load data into attributes but creates a new copy of the model attrs and adds previous as a numeric key:

Screen Shot 2013-02-19 at 8 05 38 PM

How would I get previous model state with your plugin?

Problem with backbone.localstorage on some Androids

Hi Jerome!

Found problem with methods .find of your backbone.localstorage plugin on few Androids (Android 2.3.5 Samsung Galaxy S2 and some other).
The problem connected with JSON.parse(null) of find method. With null - it cause an error "Uncaught illegal acces".

Could propose a fix with validation before parsing:

// Retrieve a model from this.data by id.
find: function(model) {
var storageData = this.localStorage().getItem(this.name+"-"+model.id);
if (storageData) {
//storageData null cause error of JSON.parse(null) on some androids
return JSON.parse(storageData);
} else {
return null;
}
},

// Return the array of all models currently in storage.
findAll: function() {
return _(this.records).chain()
.map(function(id){
var storageData = this.localStorage().getItem(this.name+"-"+id);
if (storageData) {
//storageData null cause error of JSON.parse(null) on some androids
return JSON.parse(storageData);
} else {
return null;
}
}, this)
.compact()
.value();
},

IE Error - Unable to get value of the property 'getItem': object is null or undefined

I receive the following error using localStorage in a Backbone Collection when using IE9. Works great in firefox, opera, but IE9 not so much.

"SCRIPT5007: Unable to get value of the property 'getItem': object is null or undefined
backbone.localStorage.js, line 29 character 3"

offending line --> var store = this.localStorage().getItem(this.name);

I have dom storage turned on in IE, I don't know what else I need. I'm new to backbone and the localStorage Adaptor, so hopefully I'm just doing something stupid.

I am using requirejs, but have created the necessary shim to use localStorage and like I said IE is the only issue other browser vendors works fine.

var TodosCollection = Backbone.Collection.extend({
model: Todo,
localStorage: new Backbone.LocalStorage('todos-backbone')
});

No fetch error when the localStorage is empty (collection only)

Hi,

Firstly, thanks for your plugin. I find it really useful to build my app offline mode.

But I've noticed that there is no error thrown when I fetch a collection with the localStorage empty.

A full and simple example (the localstorage is empty) :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Title</title>
        <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
        <script src="http://underscorejs.org/underscore-min.js"></script>
        <script src="http://backbonejs.org/backbone-min.js"></script>
        <script src="assets/js/libs/backbone.localstorage.js"></script>
        <script type="text/javascript">
        var MyCollection = Backbone.Collection.extend({
            localStorage : new Backbone.LocalStorage('MyCollectionStore')
        });

        var MyModel = Backbone.Model.extend({
            localStorage : new Backbone.LocalStorage('MyModelsStore')
        });

        // first example : will show "fetch success" (I expected "fetch error")
        var myCollection = new MyCollection();
        myCollection.fetch({
            success : function() {
                console.log('fetch success');
            },
            error : function() {
                console.log('fetch error');
            }
        });

        // second example : will show "fetch error" (as expected)
        var myModel = new MyModel({'id' : '01'});
        myModel.fetch({
            success : function() {
                console.log('fetch success');
            },
            error : function() {
                console.log('fetch error');
            }
        });
        </script>
    </head>

    <body>

    </body>
</html>

After executing this script, the collection is empty and there's no error thrown whereas for a model, it throws the "Record not found" error.

Is that normal ?

For the moment, in order to throw the error, I just added this condition to the plugin code (line 169):

if (resp && !_.isEmpty(resp)) {
// ...
  } else {
    errorMessage = errorMessage ? errorMessage
                                : "Record Not Found";

Thanks.

Compatibility with Backbone.js 0.5.0 and web browsers

I've just started upgrading my app to Backbone.js, so I've also upgraded Backbone.localStorage to the newest version from GitHub. Under Google Chrome everything is ok. Under Firefox models disappear from localstorage after refreshing a page. Under Opera it just doesn't work.

Am I doing this wrong or Backbone.localStorage just isn't compatible with Backbone.js 0.5.0 and new versions of browsers?

Collection fetch not returning all elements

I'm using a collection with localStorage, the elements are stored correctly, but when I fetch the collection it only returns 2 or 3 elements.

On the success function I debugged the Collection and Response and they are different (see the image, first response, then collection), the response contains all elements, but not the collection:
localcollection

I can't seem to fix it, anyone can give me a hand?

How to associate a model with an object in localStorage?

My problem is when I create a new instance of my Teacher object, and call fetch on it, it does not fetch the values in the local storage, but returning a new object with null values.

App.current_user ||= new App.Models.Teacher()
App.current_user.fetch(success: (model)->
      .....

I checked the Resource tab, and can see the items in local storage. Any clues what might be going wrong?

I should clarify that I am calling fetch after a page refresh. So my assumption is the user would leave the site and come back, and we'd restore his credentials to him.

Calling model.save() creates infinite loop on android2

Hi!

I have this model:

Search = Backbone.Model.extend
  trace: app.env.debug
  logPrefix: '[app.models.Search]:'

  localStorage: new Backbone.LocalStorage('app:search')

  expires: app.config['search_lifetime']

  defaults:
    id: 'static'
    timestamp: 0

    place:
      id: null
      name: null

    checkin: todayYMD
    checkout: afterTomorrowYMD

    adults: 2

    children: []

  initialize: ->
    @fetch(success: _.bind(@_fetched, @))
    @on('change', @updated, @)

    @log('initialize')

  ...

  updated: ->
    @set('timestamp', Date.now())
    @save()

app.models.Search = Search

When model gets updated and I try to save state to the localstorage it somehow starts an infinite loop. Only on android 2. Any idea why?

Backbone.Model.destroy() does not work the same as in Backbone.js

In backbone.js if you use model.destroy() on an object it should delete it's reference on the server.

In this environment, it does not properly work.

WORKAROUND

model.destroy(model); seems to work in a few cases, if you have not created multiple versions of the model via #48

Fetch doesn't work with some backbone 0.9.10 versions

I'm using Backbone version 0.9.10:

 Backbone.VERSION = '0.9.10';

But the options.success function uses only 1 parameter:

options.success = function(resp) {
    if (!model.set(model.parse(resp, options), options)) return false;
    if (success) success(model, resp, options);
    model.trigger('sync', model, resp, options);
  };

Then in Backbone.localStorage the model is never refreshed after a fetch. because of the code:

if (Backbone.VERSION === "0.9.10") {
    options.success(model, resp, options);
} else {
    options.success(resp);
}

I've been checking backbone repository and it looks like at some point in March the modified options.success function without upgrading the version number.
https://github.com/documentcloud/backbone/blob/83eb26f971e36e7e90e23a7f3bafc0a38b8bfdf1/backbone.js

My suggestion would be to replace the code above with something that could work in both cases:

if (Backbone.VERSION === "0.9.10") {
    if (options.success.length==3){ //for the Backbone versions where option.success uses 3 params
        options.success(model, resp, options);
    }else{
        options.success(resp);
    }
} else {
    options.success(resp);
}   

Use `url` to specify Store name for portability between storage backends

I recently developed a prototype using localStorage, and then switched to the CouchDB-based backend. However, I then had to replace all instances of Store with a url property. It seems to me that url could still be used by the localStorage backend, or am I missing something? This would make porting completely painless (it's already pretty easy, but we aim for perfection!)

Model.parse() is passed the model itself when calling save() or destroy()

When calling save() on a model, Backbone.localStorage.sync() calls store.create,update or destroy, and then passes the return value of that function to the success() callback as the response.

However, the success callback takes the response, passes it to the model's parse() function, and then takes the return value of that and passes it to model.set(). This is problematic for a two reasons:

  1. parse() has to be aware of the fact that the "response" object might actually be a reference back to the Model, which causes unnecessary coupling in the Model to the storage mechanism
  2. The value passed to parse() is different for read operations than it is for create, update or destroy operations, which causes extra complexity in parse().

The fix itself is relatively simple, but there are a few options and I'm not sure which one would be best:

  1. Return model.attributes. This would be fastest, but least similar to the normal, XHR-based sync() implementation. Models which override how they are serialized would probably not work correctly.
  2. Return model.toJSON(). This would be a little slower, but, theoretically, be as close as possible to XHR-based sync() without re-parsing the JSON. Overriding serialization would probably work fine (unless you do something really crazy).
  3. Re-read the JSON from localStorage, pass it back through JSON.parse() and return that. This seems the closest to an XHR-based sync(), but re-parsing the JSON when you don't have to seems "yucky."

My vote would be for option 2, so I'll work on getting a pull-request together for that.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.