Building Checklist.js library using HTML5 Local Storage and Backbone.js

Submitted by vadim on Fri, 09/06/2013 - 12:12
checklist.png

In this post I am going to describe how I created Checklist.js library, which turns HTML lists on your page into chekclists. It adds checkboxs to list items and stores data in the HTML5 Local Storage, so the user could to see his/her checklist(s) after reloading a page or restarting a browser.

It's continent isn't it? You can check out a live demo and a Backbone.js, Underscore.js and jQuery libraries. As for storing data in the HTML5 Local Storage I used Backbone.localStorage extension.

Let's go deep into a code!

  1. First I defined CheckBoxModel, which contains a boolean value whether a checkbox is checked or not.
      var CheckBoxModel = Backbone.Model.extend({
        defaults: {
          checked: false
        },
      });
    
  2. Then I defined CheckBoxCollection, which stores our models. Also I have introduced gain() method, which tries to get a model with a specific id or creates a new one with such id.
      // Define the collection.
      var CheckBoxCollection = Backbone.Collection.extend({
        model: CheckBoxModel,
    
        // Gets an existing model, otherwise creates new and returns.
        gain: function(id) {
          if (!this.get(id)) {
            this.add({ id: id });
          }
          return this.get(id);
        }
      });
    
  3. Now let's define CheckBoxView that renders CheckBoxModel. This view is bound to a model, so when the model is updated a view gets updated automatically and vice-verse.
      var CheckBoxView = Backbone.View.extend({
        tagName: 'input',
    
        attributes: {
          type: 'checkbox'
        },
    
        events: {
          'change': 'change'
        },
    
        initialize: function() {
          this.listenTo(this.model, 'change', this.render);
        },
    
        render: function() {
          this.$el.attr('checked', this.model.get('checked'));
    
          return this;
        },
    
        change: function () {
          this.model.save({ checked: this.$el.is(':checked') });
        }
      });
    
  4. Next, we should define ListItemView that is associated with a list item, which wraps it's content into label tag and prepends CheckBoxView.
      var ListItemView = Backbone.View.extend({
        initialize: function() {
          var checkBoxView = new CheckBoxView({ model: this.model });
          this.$el
            .prepend(checkBoxView.render().el)
            .wrapInner('
  5. And finally let's add attachChecklist() function, which attaches ListItemView to a list item and gains a model from a collection. It uses list element id and list item index to create a unique identifier for a checkbox.
  6.   var attachChecklist = function(checklist) {
        $('.checklist').each(function(index) {
    
          // Get an HTML list ID.
          var checklistId = $(this).attr('id') || '_checklist_' +  index + '_';
    
          $(this).find('>li').each(function(index) {
    
            // Attach a view to a list item.
            new ListItemView({
              el: $(this),
              model: checklist.gain(checklistId + '-' + index)
            });
          });
        });
      };
    
  7. And now the most interesting part, where we return init() function, which creates HTML5 Local Storage and passes it to the collection. To get data from the storage we should call fetch() method of the collection.
      return {
        init: function(storageId) {
    
          // Set falback storage ID based on the current URL.
          storageId = storageId ||  window.location.origin + window.location.pathname;
    
          // Create local storage with given ID.
          _.extend(CheckBoxCollection.prototype, {
            localStorage: new Backbone.LocalStorage(storageId)
          });
    
          // Create collection instance.
          this.checklist = new CheckBoxCollection();
    
          // Fetch data from the storage.
          this.checklist.fetch({ success: attachChecklist });
        }
      }
    

Here it is! Our extension works as expected. You can check out a live demo and find more interesting recipes about Backbone models, collections, views, REST and HTML5 Local Storage in the Backbone.js Cookbook.

35 comments

I actually knowledgeable

Submitted by Belda (not verified) on Thu, 07/24/2014 - 13:18.

I actually knowledgeable learning it, you will be an outstanding author. https://archive.org/details/TaoOfBadassReview

News programmes have suddenly

Submitted by Anonymous (not verified) on Fri, 07/25/2014 - 10:16.

News programmes have suddenly become hot property and are vying for attention with other popular programmes telecast in different channels. All major television broadcasters are including at least one news channel to their bouquet. www.7dnews.org

Many in the United States are

Submitted by Anonymous (not verified) on Fri, 07/25/2014 - 10:16.

Many in the United States are happy to see the Chinese workers making more money for making the goods we buy from them, or from our own companies with factories there. Some cite that it will bring back US factory jobs. www.allconsumingnews.org

Before making a firm decision

Submitted by Anonymous (not verified) on Fri, 07/25/2014 - 10:16.

Before making a firm decision on a plan that looks attractive consult with a licensed agent about the possibilities that might happen after you submit an application to the insurer. In this article I will explain the possible scenarios that can happen once you apply. www.broadhealth.org

The term "health insurance"

Submitted by Anonymous (not verified) on Fri, 07/25/2014 - 10:16.

The term "health insurance" is commonly used in the United States to describe any program that helps pay for medical expenses, whether through privately purchased insurance, social insurance or a non-insurance social welfare program funded by the government. www.coimbrahealth.org

Researchers from the Medical

Submitted by Anonymous (not verified) on Fri, 07/25/2014 - 10:16.

Researchers from the Medical University of South Carolina in Charleston analyzed 5,021 participants in the National Health and Nutrition examination Survey 1999-2000 (NHANES 99-00), which was conducted by the National Center for Health Statistics to collect information concerning the health and diet of American men and women. www.crphealth.org

Yeah

Submitted by wendy (not verified) on Wed, 07/23/2014 - 10:51.

Our organization is built on relationships, and Software Tailor fits right in to that model. It is apparent that they consider their role to be helping us make our organization function better. I consider this a long-term partnership.
Software Outsourcing HK

Really informative

Submitted by Daniel (not verified) on Tue, 07/22/2014 - 20:38.

Really informative blog.Really looking forward to read more. Great. http://www.dietmythsandfacts.com/2013/10/old-school-new-body-user-reviews.html

Ngiring Nangkring

Submitted by obat kanker kelenjar getah bening (not verified) on Tue, 07/08/2014 - 06:31.

the natural world continues to undergo relational transformation and this is the obat sinusitis alami world of our experience. we invent words like obat anemia 'technocracy', 'capitalism', 'sovereigntism', 'authoritarianism', 'christianity', 'islam' to obat maag point to 'belief systems' obat darah tinggi alami which involve 'rules' and 'regulating' of one's behaviour through the intellect obat stroke alami. sovereigntism requires that we pay taxes to ace maxs a central authority to fund the hiring of police and military to ensure that we continue to obat jantung koroner alami pay taxes

What can make the same as

Submitted by Meme (not verified) on Thu, 07/03/2014 - 09:22.

What can make the same as well could always change the best thing to happen. - Ellerslie Mission Society

Great job here. I really

Submitted by Mariela (not verified) on Wed, 06/25/2014 - 16:38.

Great job here. I really enjoyed what you had to say. http://www.dietmythsandfacts.com/2014/06/pregnancy-miracle-book.html http://www.dietmythsandfacts.com/2014/06/adonis-golden-ratio-review.html

This article gives the light

Submitted by Tony (not verified) on Mon, 06/23/2014 - 13:33.

This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. https://archive.org/details/WhatMenSecretlyWantJamesBauer https://archive.org/details/VenusFactorDiet

7 meterz

Submitted by Anonymous (not verified) on Wed, 07/02/2014 - 12:53.

areterbartema thanks infonya
keren
Agen Bola, Agen Bola Online, situs taruhan bola, Agen judi bola, Bandar Bola, Bandar Taruhan Bola

Dank u voor deze gemakkelijke

Submitted by Ilyaas Stoelwinder (not verified) on Sat, 06/21/2014 - 11:42.

Dank u voor deze gemakkelijke en eenvoudige richtlijnen, het helpt me mijn best mijn eigen werk te doen ... voor uw toekomstige nieuwste post en artikelen die ik wil delen met goede bloed whatsapp downloaden, ben ik geloof zeker dat het je zal helpen bij het toekomstig onderzoek!

DGGP Pvt. Ltd. is a leading

Submitted by ram14 (not verified) on Sat, 05/31/2014 - 14:22.

DGGP Pvt. Ltd. is a leading manufacturer of Guar Fast Hydration Polymers used in Gas Oil Fields fracturing Industry in the world.
Natural polymers manufacturers and suppliers
Shell Energy

It's a useful information i

Submitted by Software house (not verified) on Sat, 01/11/2014 - 17:38.

It's a useful information i am glad to read it over here i will keep visiting this site thanks for sharing.
Software House

*very nice post, i certainly

Submitted by denisa13 (not verified) on Tue, 02/11/2014 - 15:24.

*very nice post, i certainly love this website, keep on itweb hosting

Very informative article so

Submitted by sonia (not verified) on Sat, 03/29/2014 - 00:18.

Very informative article so many interesting things i found here which increase my knowledge so much. inregistrare domenii

In this post I am going to

Submitted by Anonymous (not verified) on Fri, 11/29/2013 - 04:27.

In this post I am going to describe how I created Checklist.js library, which turns I really enjoyed this brilliant blog. Please keep them coming. Greets !This is a in fact good read for me, Must admit that you are human being of the best bloggers I ever saw. Thanks for posting this informative article... the closer seasons 1-7 dvd box set| lie tome Seasons 1-3 DVD Box Set| star wars the clone wars Seasons 1-5 DVD Box Set|star wars the clone wars Seasons 1-5 DVD Box Set| 90210 Seasons 1-5 DVD Box Set| Falling Skies Seasons 1-3 dvd box set

And finally let's add

Submitted by Anonymous (not verified) on Fri, 11/29/2013 - 04:25.

And finally let's add attachChecklist() function, which attaches ListItemView to a list item and gains a model from a collection. It uses list element id and list item index to create a unique identifier for a checkbox. This is excellent post. Its having good description regarding this topic. It is informative and helpful. I have known much information from this. Thanks for sharing. dexter Seasons 1-7 DVD Box Set|One Tree Hill Season 9 DVD Box Set|Friends Seasons 1-10 DVD Box set|American Horror Story Seasons 1-2 DVD Box Set| CSI Miami Seasons 1-10 DVD Box Set|The Wire Seasons 1-5 dvd box set

Very good and interesting article.

Submitted by Joana (not verified) on Thu, 01/23/2014 - 23:47.

*There is noticeably a bundle to know about this. I assume you made certain nice points in features also.Personalized Pillows

nteresting recipes about

Submitted by Anonymous (not verified) on Fri, 11/29/2013 - 04:24.

nteresting recipes about Backbone models, collections, views, REST and HTML5 Local Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase Cheap Walt Disney's 100 Years Of Magic 172 Discs DVD Boxset|chuck Seasons 1-5 DVD Box Set|cane Seasons 1-5 DVD Box Set| True Blood Season 6 DVD Box Set| Suits Seasons 1-2 DVD Box Set|Rosetta Stone V3 Spanish (Latin America) Levels 1-5

sbobet asia

Submitted by sbobet (not verified) on Sun, 09/08/2013 - 20:39.

May I simply say what a aid to search out somebody who truly knows what they are really discussing about on the web. You positively understand learn how to convey a difficulty to light and make it important. Extra people must learn this and perceive this facet of the story. I am unable to consider you're less standard because you definitely hold the gift.
agen bola sbobet
sbobet

*Oh my goodness! an amazing

Submitted by dalia (not verified) on Sun, 02/16/2014 - 14:36.

*Oh my goodness! an amazing article dude. Thank you However I am experiencing issue with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anyone who knows kindly respond. Thnkx
inregistrare domenii

Thanks for the post

Submitted by meluta (not verified) on Tue, 02/04/2014 - 11:51.

*This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great! ipad mini cases

Fashion Designing Institute in Jaipur

Submitted by Fashion Designing Institute in Jaipur (not verified) on Thu, 09/26/2013 - 11:39.

You blog post is just completely quality and informative. Many new facts and information which I have not heard about before. Keep sharing more blog posts.

Can I just say what a relief

Submitted by jenica (not verified) on Sun, 02/09/2014 - 15:21.

Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.
ipad air cases

he next time I read a blog, I

Submitted by matei45 (not verified) on Sun, 02/09/2014 - 15:24.

he next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.
personalized gifts

*Aw, this was a really nice

Submitted by helena43 (not verified) on Sun, 02/16/2014 - 14:37.

*Aw, this was a really nice post. In idea I would like to put in writing like this additionally – taking time and actual effort to make a very good article… but what can I say… I procrastinate alot and by no means seem to get something done. personalized watches for men

i totally agree with you,

Submitted by Cancer cure (not verified) on Thu, 12/12/2013 - 14:56.

i totally agree with you, This is really a great blog i got very useful information over here thanks for sharing it with us.
Cancer Cure

i totally agree with you,

Submitted by Cancer cure (not verified) on Thu, 12/12/2013 - 14:55.

i totally agree with you, This is really a great blog i got very useful information over here thanks for sharing it with us.

*There is noticeably a bundle

Submitted by monica (not verified) on Wed, 01/29/2014 - 12:42.

*There is noticeably a bundle to know about this. I assume you made certain nice points in features also The Best Spinner

Great Post

Submitted by monica (not verified) on Wed, 01/29/2014 - 12:39.

*Would you be interested in exchanging links?gazduire web

*I’m impressed, I must say.

Submitted by denisa13 (not verified) on Tue, 02/11/2014 - 15:23.

*I’m impressed, I must say. Really rarely do I encounter a blog that’s both educative and entertaining, and let me tell you, you have hit the nail on the head. Your idea is outstanding; the issue is something that not enough people are speaking intelligently about.
yellow throw pillows

Nice Post

Submitted by Anonymous (not verified) on Thu, 07/17/2014 - 22:19.

Thank u.. Its very help :)

| tiket pesawat murah | homestay |