1

I'm new to backbone, I'm following a tutorial and I'm trying to use local storage as a database, but I wasn't able to find an article that explains about how to use them together.

This is the code:

$(function() {
window.app = {
    Models: {},
    Collections: {},
    Views: {}
};

window.template = function(id) {
    return _.template($('#' +  id).html());
}

//Item model
app.Models.Item = Backbone.Model.extend({
    defaults: {
        title: ''
    }
});




//items collection
app.Collections.ItemsList = Backbone.Collection.extend({
    // reference to the model
    model: app.Models.Item,

    //save all items in local storage
    localStorage: new Backbone.LocalStorage('items-store')
});




//the items list
app.Views.Items = Backbone.View.extend({
    tagName: 'ul',

    initialize: function() {
        this.collection.on('add', this.addOne, this);
    },

    render: function() {
        //for each element in the collection call the add one function
        this.collection.each(this.addOne, this);
        return this;
    },

    addOne: function(itemModel) {
        // create a new child view
        var itemView = new app.Views.Item({model: itemModel});
        //append to the root element
        this.$el.append(itemView.render().el);
    }
});




// one item view
app.Views.Item = Backbone.View.extend({
    //tag name of the view
    tagName: 'li',

    template: template('itemTemplate'),

    events: {
        'click .edit': 'editModel'
    },

    initialize: function() {
        //rerender the model whet the text is changed
        this.model.on('change', this.render, this);
    },

    render: function() {
        //render the template
        var template = this.template(this.model.toJSON());
        //tale the list item and populate it with the associated model
        this.$el.html(template);
        return this;
    },

    editModel: function() {
        //prompt the user to change the text
       var newValue = prompt('You want to change the text?', this.model.get('title'));
       //if cancel is pressed
       if(!newValue) { return};
       //add the new value to the model
       this.model.set('title', newValue);
    }
});




//add new item view
app.Views.AddItem = Backbone.View.extend({
    el: '#addItem',

    collection: new app.Collections.ItemsList,

    events: {
        'submit' : 'submit'
    },

    initialize: function() {
        this.collection.fetch({reset: true});

        //call the Items view
        var items = new app.Views.Items({collection: this.collection});
        //populate the itemsList  with the ul
        $('#itemsList').html(items.render().el);

        //this is just for demo purpose
        this.store();
    },

    submit: function(e) {
        e.preventDefault();
        //get the value from the input
        var newTaskTitle = this.$el.find('input[type=text]').val();
        //create a new model with the value from newTaskTitle
        var item = new app.Models.Item({title: newTaskTitle});
        //create the collection in order to trigger the localstorage plugin
        this.collection.create(item);

        //this is just for demo purpose
        this.store();
    },

    store: function() {
        //this is just for demo purpose
        //items in local storage
        for(var i = 0; i < localStorage.length; i++) {
            var obj = localStorage.getItem(localStorage.key(i));
            $('.number span').html(localStorage.length);
            $('#localStorage').append('<div>' + i + '---' + obj + '</div>');

        }

    }
});

//dummy collection
var itemsCollection = new app.Collections.ItemsList([
    {
        title : 'go home'
    },
    {
        title : 'go home1'
    },
    {
        title : 'go home2'
    }
]);

//call the view with the dummy collection
// var addItems = new app.Views.AddItem({collection: itemsCollection});

// //call the view without the collection
var addItems = new app.Views.AddItem();  
//end of function
}());

Edit: The code was changed, and the jsfiddle updated: http://jsfiddle.net/9z0cc6r8/1/

I found out that the backbone localstorage plugin saves models to the browser's local storage like this: this.collection.create(item); but if I refresh the page, the items desapear from the colelction and they aren't rendered on the page again.

Does any one know how I can display my items on the page from the local storage? I still need acces to the model after doing that because I want to perform edit and delete actions on them.

P.S. Seems that on js fiddle it works fine. But on local it dosen't.

  • try to use localstorage alone & then try to use backbone alone, when you think you're good in both, then try to integrate. – coding_idiot May 10 '15 at 19:14
  • You'll probably want to [reimplement the `sync()` method of your Collection](http://backbonejs.org/#Collection-sync). MDN about the [Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage) – try-catch-finally May 10 '15 at 19:28

1 Answers1

0

I'm using this lib: https://github.com/jeromegn/Backbone.localStorage

And that's how I define it in a collection:

localStorage: new Store("your-storage")

After that models will automatically works with localStorage.

blues911
  • 840
  • 8
  • 9