SlideShare uma empresa Scribd logo
1 de 11
Baixar para ler offline
Web Storage

       Dylan Schiemann (@dylans)
       SitePen, Inc.
       HTML5 Code Camp, October, 2010


       © SitePen, Inc. All Rights Reserved

Sunday, October 17, 2010
© SitePen, Inc. All Rights Reserved

Sunday, October 17, 2010
Web Storage Timeline

                   Cookies
                   Flash Storage
                   Dojo Offline/Storage, Google Gears
                   localStorage and sessionStorage
                   window[‘name’] hack
                   WebDatabase and IndexedDB




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL API

                   Currently supported by Safari, Chrome, and Opera. Will not
                   be supported by Mozilla.
                   SQL, query-based transactions
                   Asynchronous interactions
                   Editor’s Draft: http://dev.w3.org/html5/webdatabase/
                   Will be easy to use for those well-versed in SQL




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL: Open Connection, Create Table

          // Connect to the db
          var db = window.openDatabase("MyDB", "", "My database", 1024);

          // If the db has not been initialized for this user...
          if (db.version != "1") {

                  // User's first visit. Initialize database.
                  db.changeVersion(db.version, "1", function(tx) {

                           // Create "users" table
                           tx.executeSql("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT);");

                  }, null, function() {

                           // Success!
                           console.log('success!');
                  });
          }
          else {

                  // DB already created, move on....
          }




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL: Add Records

          // Connect to the db
          var db = window.openDatabase("MyDB", "1", "My database", 1024);

          // Create a transaction
          db.transaction(function(tx) {

                  // Execute a SQL statement
                  tx.executeSql("INSERT INTO users (name) VALUES (:name);", // sql
                              [{ name: 'Dylan'}], // Object (data)
                              function(tx, results) { // Success!
                                  console.log('Added user. ID: ' + results.insertId,results);
                              },
                              function(tx,e) { // Error!
                                  console.log('Error! ',e);
                              }
                  );
          });




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL: Retrieve Records

          // Connect to the db
          var db = window.openDatabase("MyDB", "1", "My database", 1024);

          // Create a transaction
          db.readTransaction(function(tx) {

                  // Search for all users
                  tx.executeSql("SELECT * FROM users", [], function(tx, results) {

                           // Get result rows
                           var rows = results.rows;

                           // For each row
                           for(x = 0; x < rows.length; x++) {

                                    // Get the user information!
                                    var user = rows.item(x);
                                    console.log('Found user: ' + user.name);
                           }
                  });
          });




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB API

                   Actively developed by Mozilla
                   Initial support will begin with Firefox 4 (4b6 has issues)
                   Currently a working draft with the W3C
                   Not SQL-based; JavaScript object storage with indexes
                   Asynchronous interactions
                   Working Draft: http://www.w3.org/TR/IndexedDB/
                   Dojo and Persevere implement it




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB: Open Connection, Create Table

          // Attempt to open a database
          var request = window.indexedDB.open("MyDB","My database"); // DB name, description

          // Add "success" handling
          request.onsuccess = function(event) {

                  // Check to see if the database has been created
                  if(event.result.version != "1") { // not created

                           // Create users table (table name, key, autoincrement?)
                           var tableRequest = db.createObjectStore("users","id",true);

                           // Success!
                           tableRequest.onsuccess = function() {

                                    // Save as created!
                                    db.setVersion("1");
                           };
                  }
          };

          // Account for errors
          request.onerror = function(event) {
              //handle the error
          };


    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB: Create a Store with Data

          // Attempt to open a database
          var request = window.indexedDB.open("MyDB","My database"); // DB name, description

          // Add "success" handling
          request.onsuccess = function(event) {
              // Grab a store
              var objectStore = event.result.objectStore("users");

                  // Add a record
                  objectStore.add({ name: "Dylan", role:"CEO" }).onsuccess(function(){
                      // Success!
                      console.log("Record saved!");
                  });

                  // Add another record
                  objectStore.add({ name: "David", role:"Engineer" }).onsuccess(function(){
                      // Success!
                      console.log("Second record saved!");
                  });

          };




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB: Retrieve All Data

          // Attempt to open a database
          var request = window.indexedDB.open("MyDB","My database"); // DB name, description

          // Add "success" handling
          request.onsuccess = function(event) {
              // Open a cursor on the users store
              cursorRequest = event.result.objectStore("users").openCursor();
              // If successful...
              cursorRequest.onsuccess = function(e) {

                           // Grab the cursor
                           var cursor = e.cursor;

                           // If cursor is null, exit
                           if(!cursor) { return; }

                           // Get reference to the object at the cursor position
                           var record = e.cursor.value;

                           // Log object to the console
                           console.log("User: " + record.name + "; Role:   " + record.role);

                           // Continue!
                           cursor.continue();
                  };
          };

    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010

Mais conteúdo relacionado

Mais procurados

Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Arian Gutierrez
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
kchodorow
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocial
Thomas Roger
 

Mais procurados (20)

Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Hidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-PersistenceHidden pearls for High-Performance-Persistence
Hidden pearls for High-Performance-Persistence
 
2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Couchdb w Ruby'm
Couchdb w Ruby'mCouchdb w Ruby'm
Couchdb w Ruby'm
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
 
Diving into php
Diving into phpDiving into php
Diving into php
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocial
 
занятие8
занятие8занятие8
занятие8
 
Web2py
Web2pyWeb2py
Web2py
 
Introduction to the new official C# Driver developed by 10gen
Introduction to the new official C# Driver developed by 10genIntroduction to the new official C# Driver developed by 10gen
Introduction to the new official C# Driver developed by 10gen
 
Redis the better NoSQL
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQL
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
 
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
 
iOS5 NewStuff
iOS5 NewStuffiOS5 NewStuff
iOS5 NewStuff
 
最近 node.js 來勢洶洶, 怎麼辦? 別怕, 我們也有秘密武器 RingoJS!
最近 node.js 來勢洶洶, 怎麼辦? 別怕, 我們也有秘密武器 RingoJS!最近 node.js 來勢洶洶, 怎麼辦? 別怕, 我們也有秘密武器 RingoJS!
最近 node.js 來勢洶洶, 怎麼辦? 別怕, 我們也有秘密武器 RingoJS!
 
SWORD & ResourceSync - Stuart Lewis
SWORD & ResourceSync - Stuart Lewis SWORD & ResourceSync - Stuart Lewis
SWORD & ResourceSync - Stuart Lewis
 
Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)
 

Semelhante a Intro to HTML5 Web Storage

Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross
 
Terrastore - A document database for developers
Terrastore - A document database for developersTerrastore - A document database for developers
Terrastore - A document database for developers
Sergio Bossa
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
 
Persistent Offline Storage White
Persistent Offline Storage WhitePersistent Offline Storage White
Persistent Offline Storage White
Alexei White
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
Pedro Morais
 

Semelhante a Intro to HTML5 Web Storage (20)

Local Storage
Local StorageLocal Storage
Local Storage
 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Organizing Code with JavascriptMVC
Organizing Code with JavascriptMVCOrganizing Code with JavascriptMVC
Organizing Code with JavascriptMVC
 
Terrastore - A document database for developers
Terrastore - A document database for developersTerrastore - A document database for developers
Terrastore - A document database for developers
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Persistent Offline Storage White
Persistent Offline Storage WhitePersistent Offline Storage White
Persistent Offline Storage White
 
Parse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & TricksParse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & Tricks
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Hibernate
Hibernate Hibernate
Hibernate
 
OrientDB introduction - NoSQL
OrientDB introduction - NoSQLOrientDB introduction - NoSQL
OrientDB introduction - NoSQL
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net Core
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on Playframework
 

Mais de dylanks (9)

Building a Modern JavaScript Framework by James Milner
Building a Modern JavaScript Framework by James MilnerBuilding a Modern JavaScript Framework by James Milner
Building a Modern JavaScript Framework by James Milner
 
London Ajax User Group Meetup: Vector Graphics
London Ajax User Group Meetup: Vector GraphicsLondon Ajax User Group Meetup: Vector Graphics
London Ajax User Group Meetup: Vector Graphics
 
Web Vector Graphics
Web Vector GraphicsWeb Vector Graphics
Web Vector Graphics
 
Dojo Mobile
Dojo MobileDojo Mobile
Dojo Mobile
 
Intro to WebSockets and Comet
Intro to WebSockets and CometIntro to WebSockets and Comet
Intro to WebSockets and Comet
 
HTML5: Toolkits and Gaps
HTML5: Toolkits and GapsHTML5: Toolkits and Gaps
HTML5: Toolkits and Gaps
 
Introduction to Canvas and Native Web Vector Graphics
Introduction to Canvas and Native Web Vector GraphicsIntroduction to Canvas and Native Web Vector Graphics
Introduction to Canvas and Native Web Vector Graphics
 
London Ajax User Group Meetup: Comet Panel
London Ajax User Group Meetup: Comet PanelLondon Ajax User Group Meetup: Comet Panel
London Ajax User Group Meetup: Comet Panel
 
SWDC 2010: Programming to Patterns
SWDC 2010: Programming to PatternsSWDC 2010: Programming to Patterns
SWDC 2010: Programming to Patterns
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Intro to HTML5 Web Storage

  • 1. Web Storage Dylan Schiemann (@dylans) SitePen, Inc. HTML5 Code Camp, October, 2010 © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 2. © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 3. Web Storage Timeline Cookies Flash Storage Dojo Offline/Storage, Google Gears localStorage and sessionStorage window[‘name’] hack WebDatabase and IndexedDB © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 4. WebSQL API Currently supported by Safari, Chrome, and Opera. Will not be supported by Mozilla. SQL, query-based transactions Asynchronous interactions Editor’s Draft: http://dev.w3.org/html5/webdatabase/ Will be easy to use for those well-versed in SQL © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 5. WebSQL: Open Connection, Create Table // Connect to the db var db = window.openDatabase("MyDB", "", "My database", 1024); // If the db has not been initialized for this user... if (db.version != "1") { // User's first visit. Initialize database. db.changeVersion(db.version, "1", function(tx) { // Create "users" table tx.executeSql("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT);"); }, null, function() { // Success! console.log('success!'); }); } else { // DB already created, move on.... } © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 6. WebSQL: Add Records // Connect to the db var db = window.openDatabase("MyDB", "1", "My database", 1024); // Create a transaction db.transaction(function(tx) { // Execute a SQL statement tx.executeSql("INSERT INTO users (name) VALUES (:name);", // sql [{ name: 'Dylan'}], // Object (data) function(tx, results) { // Success! console.log('Added user. ID: ' + results.insertId,results); }, function(tx,e) { // Error! console.log('Error! ',e); } ); }); © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 7. WebSQL: Retrieve Records // Connect to the db var db = window.openDatabase("MyDB", "1", "My database", 1024); // Create a transaction db.readTransaction(function(tx) { // Search for all users tx.executeSql("SELECT * FROM users", [], function(tx, results) { // Get result rows var rows = results.rows; // For each row for(x = 0; x < rows.length; x++) { // Get the user information! var user = rows.item(x); console.log('Found user: ' + user.name); } }); }); © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 8. IndexedDB API Actively developed by Mozilla Initial support will begin with Firefox 4 (4b6 has issues) Currently a working draft with the W3C Not SQL-based; JavaScript object storage with indexes Asynchronous interactions Working Draft: http://www.w3.org/TR/IndexedDB/ Dojo and Persevere implement it © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 9. IndexedDB: Open Connection, Create Table // Attempt to open a database var request = window.indexedDB.open("MyDB","My database"); // DB name, description // Add "success" handling request.onsuccess = function(event) { // Check to see if the database has been created if(event.result.version != "1") { // not created // Create users table (table name, key, autoincrement?) var tableRequest = db.createObjectStore("users","id",true); // Success! tableRequest.onsuccess = function() { // Save as created! db.setVersion("1"); }; } }; // Account for errors request.onerror = function(event) { //handle the error }; © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 10. IndexedDB: Create a Store with Data // Attempt to open a database var request = window.indexedDB.open("MyDB","My database"); // DB name, description // Add "success" handling request.onsuccess = function(event) { // Grab a store var objectStore = event.result.objectStore("users"); // Add a record objectStore.add({ name: "Dylan", role:"CEO" }).onsuccess(function(){ // Success! console.log("Record saved!"); }); // Add another record objectStore.add({ name: "David", role:"Engineer" }).onsuccess(function(){ // Success! console.log("Second record saved!"); }); }; © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 11. IndexedDB: Retrieve All Data // Attempt to open a database var request = window.indexedDB.open("MyDB","My database"); // DB name, description // Add "success" handling request.onsuccess = function(event) { // Open a cursor on the users store cursorRequest = event.result.objectStore("users").openCursor(); // If successful... cursorRequest.onsuccess = function(e) { // Grab the cursor var cursor = e.cursor; // If cursor is null, exit if(!cursor) { return; } // Get reference to the object at the cursor position var record = e.cursor.value; // Log object to the console console.log("User: " + record.name + "; Role: " + record.role); // Continue! cursor.continue(); }; }; © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010