jeromegn / Backbone.localStorage

A localStorage adapter for Backbone.js
MIT License
1.9k stars 681 forks source link

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

Closed angely-dev closed 11 years ago

angely-dev commented 11 years ago

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.

jeromegn commented 11 years ago

I don't believe it to be an error when a collection is simply empty. It's common to have an empty set of data for something within your app.