Convert cookies into a Backbone collection

I had a need to look at my cookies in a Backbone project and decided that I needed them in a Collection and here is how I did it.
  //Create a base ModelClass
  var cookieModelClass = Backbone.Model.extend({

  });

//Create the collection
   var CookieCollectionClass = Backbone.Collection.extend({
	   model: cookieModelClass,
	   initialize: function(){
                   //Grab the cookies and go to work
 		   var ca = document.cookie.split(';');
			for(var i=0; i<ca.length; i++)
			{
			         var cookie = ca[i].trim().split("=");
					 this.add(new cookieModelClass({
					   name: cookie[0],
					   value: cookie[1]
					  }));

			}
	}
    });

//To retrive
var cookies = new CookieCollectionClass();
cookies.where({name: 'user_email'})[0].get("value")
Advertisements
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: