Coder Social home page Coder Social logo

localforage-backbone's Introduction

localForage Backbone Build Status

Backbone.js driver for the localForage offline storage library.

Install with bower:

bower install localforage-backbone

Run tests with grunt:

grunt test

Submit issues, pull requests, etc. if something is up! <3

Usage

This library lets you override the sync() method on your collections and models so they're saved to localForage instead of a REST server. Simply override your objects' sync() method with the namespace for your model:

var MyModel = Backbone.Model.extend({
    sync: Backbone.localforage.sync('MyModel')
});

var MyCollection = Backbone.Collection.extend({
    model: MyModel,
    sync: Backbone.localforage.sync('MyCollection')
});

Now whenever you save your collections or models, they'll be saved with localForage!

Warning

This library is only about overriding Backbone.sync, which means that calling collection.remove(model) won't update the offline storage.

The Backbone.Collection.remove function is only about removing a model from a collection, to clean up all references and event listeners, but does not involve a sync operation.

If you want to destroy a model, you should use this code instead:

// retrieve a model by its id and destroy it
collection.get(id).destroy();

// or

// retrieve a model by its index in the collection and destroy it
collection.at(index).destroy();

License

This program is free software; it is distributed under an Apache License.


Copyright (c) 2014 Mozilla (Contributors).

localforage-backbone's People

Contributors

chatgris avatar iamolivinius avatar magalhas avatar stephanebachelier avatar t1st3 avatar tofumatt 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

Watchers

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

localforage-backbone's Issues

Update example

An issue might not be the best way, but it's just to let you know that I'm currently working on the example.

The idea is to have a full example to play with (create, update, delete).

Discussion: More efficient use of localstorage options

Right now all entries into a Backbone collection get concatenated into a single string. A screenshot of how a collection (with models) is represented is attached here:

screenshot from 2014-03-17 22 26 57

Although this might be efficient (you're writing a single string!) it's not very friendly to debug. In a server database it would be very common to split the models up so that they each have their own key.

Now without rushing things (this would take a while to implement), what are your thoughts on splitting collections and models up?

Test and upgrade LocalForage version

Hello.

I'm installing localForage and localForage-backbone with Bower and noted a conflict between the last version of localForage (0.4) with that localForage-backbone requires (0.1).

Can anyone test and upgrade the version with the new version of localForage?

Thanks.

Destroying models doesn't remove reference from collection.

Collection is updated only on .save() and destroying models leaves orphaned model ids in the collection.

Below is a cumbersome workaround that kind of works, but this should be fixed.

collection.remove(model);
model.collection = collection;
model.save();
model.destroy();

how to add limits, page_no etc

I want to select a few items from the collection based on criteria provided.

I modified findAll method but for some reason it does not seem to work. However, findAll works fine.

        MyfindAll: function(collection, callbacks) {
            localforage.getItem( collection.sync.localforageKey, 
                         function( err, data ){
                if (!err && data && data.length) {
                    var done = function() {
                      if( callbacks.success ){
               var options  = _.defaults( callbacks.data || {}, 
                                   { page_no:0,       limit:5, 
                                 asc_desc:"desc", order_by:"id" });
            var sorted = _.sortBy( data, function( model ){  
              return typeof model.id === 'undefined' ?
                    Number.MAX_SAFE_INTEGER : model.id ;
            });
            var ordered = options.asc_desc === 'desc' ? 
                          sorted.reverse() : sorted;
            var offset  = options.limit * options.page_no;
            console.log( 'Items: ' + 
                        JSON.stringify( ordered.slice( offset, options.limit )));
            callbacks.success(ordered.slice( offset, options.limit ));
                      }
                    };//.done()

                    // Only execute `done` after getting all of the
                    // collection's models.
                    done = _.after(data.length, done);

                    var onModel = function(i, err, model) {
                        data[i] = model;
                        done();
                    };

                    for (var i = 0; i < data.length; ++i) {
                        localforage.getItem(data[i], _.partial(onModel, i));
                    }
                } else {
                    data = [];
                    if (callbacks.success) {
                        callbacks.success(data);
                    }
                }
            });
        }

The console log prints items on the console but collection view is not being populated if I use this method.

Any ideas what could be wrong with this approach?

Expose localforage.config? (patch)

It would be handy, at least for dev, to expose the localforage.config method — if you like the patch (I'm not sure I do), I can make a pull request if required.

--- bower_components/localforage-backbone/dist/localforage.backbone.js  2015-02-24 13:26:05.000000000 +0100
+++ bower_components/localforage-backbone/dist/localforage.backbone.patched.js  2015-02-24 13:26:17.000000000 +0100
@@ -53,6 +53,9 @@
     // For now, we aren't complicated: just set a property off Backbone to
     // serve as our export point.
     Backbone.localforage = {
+        getLocalforage: function () {
+            return localforage
+        },
         sync: function(name) {
             var _this = this;
             var sync = function(method, model, options) {

Documentation / Examples

snippet of documentation shown below and same shows in the 'usage' part of README.md. Why does the model become a Collection extend? Have also successfully ran the example application, but if I create 2+ items and exit the browser, restart .. only the last item populates.

// The basics of how to use this library is that it lets you override the
// sync method on your collections and models to use localForage. So
//
// var MyModel = Backbone.Model.extend({})
//
// becomes
//
// var MyModel = Backbone.Collection.extend({
// sync: Backbone.localforage.sync('ModelNamespace')
// });

Upgrade version

@tofumatt It would be really great to add a new tag since this library has been updated to last localforage version :)

Tests not distributed via Bower

bower.json has test* in the ignore list — is this intentional?
I'm trying to get items removed from a collection using the example code from the README.md, and would like to see the modify the test and see it pass locally.

"this.sync.localforageKey" doesn't get updated

I noticed a strange behavior in the sync() method when using localFrage-backbone. It only set the this.sync.localforageKey one time. After creating and fetching another model, it never updated this key.

To fix this I added on line in the sync method:

this.sync.localforageKey = name + "/" + model.id

Add after line 67 in localforage.backbone.js

Did anyone noticed the same issue?
After adding this it works for me.

Pull request?

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.