Skip to content

Step 9 - Store data in localStorage

Latest
Compare
Choose a tag to compare
@dmytroyarmak dmytroyarmak released this 05 Feb 15:46
  1. Install Backbone.localStorage

    bower install Backbone.localStorage --save
    
  2. Add script in index.html

      <script src="vendor/Backbone.localStorage/backbone.localStorage.js"></script>
    
  3. Add localStorage to ContactManager.Collections.Contacts

    ContactManager.Collections.Contacts = Backbone.Collection.extend({
      model: ContactManager.Models.Contact,
      localStorage: new Backbone.LocalStorage('contacts')
    });
    
  4. Start app without sample data

      <script>
        $(function() {
          ContactManager.start();
        });
      </script>
    
    var contacts = new ContactManager.Collections.Contacts(),
    
  5. Fetch collection in controller

      this._contacts.fetch();
    
  6. Create sample data if collection is empty

      if (this._contacts.isEmpty()) {
        this._createSampleData();
      }
    
    _createSampleData: function() {
      _.each([
        {
          id: 1,
          name : 'Terrence S. Hatfield',
          tel: '651-603-1723',
          email: 'TerrenceSHatfield@rhyta.com',
          avatar: '1.jpg'
        },
        {
          id: 2,
          name : 'Chris M. Manning',
          tel: '513-307-5859',
          email: 'ChrisMManning@dayrep.com',
          avatar: '2.jpg'
        },
        {
          id: 3,
          name : 'Ricky M. Digiacomo',
          tel: '918-774-0199',
          email: 'RickyMDigiacomo@teleworm.us',
          avatar: '3.jpg'
        },
        {
          id: 4,
          name : 'Michael K. Bayne',
          tel: '702-989-5145',
          email: 'MichaelKBayne@rhyta.com',
          avatar: '4.jpg'
        },
        {
          id: 5,
          name : 'John I. Wilson',
          tel: '318-292-6700',
          email: 'JohnIWilson@dayrep.com',
          avatar: '5.jpg'
        },
        {
          id: 6,
          name : 'Rodolfo P. Robinett',
          tel: '803-557-9815',
          email: 'RodolfoPRobinett@jourrapide.com',
          avatar: '6.jpg'
        }], function(contact) {
          this._contacts.create(contact);
        }, this);
    }
    
  7. Use destroy instead of remove

    this.listenTo(contactsView, 'itemview:delete:clicked', function(contactView) {
      contactView.model.destroy();
    });
    
  8. Use save instead of set

      this.listenTo(editContactForm, 'form:submitted', function(attrs) {
        contact.save(attrs);
        this.showContacts();
      });
    
  9. Remove avatar generator from ContactManager.Models.Contact

  10. Change contact creation code

      this.listenTo(newContactForm, 'form:submitted', function(attrs) {
        attrs.avatar = _.random(1, 15) + '.jpg';
        this._contacts.create(attrs);
        this.showContacts();
      });
    

Difference