Gears

Database

  1. The HTML page:
    <html>
    <head>
    <title>Gears Database Demo</title>
    <link rel="stylesheet" type="text/css" href="sample.css">
    </head>
    
    <body>
    <h1>Gears Database Demo</h1>
    <div id="view-source">&nbsp;</div>
    
    <form onsubmit="handleSubmit(); return false;">
    
      <b>Enter a phrase to store in the database:</b>&nbsp;<br>
      <table>
        <tr>
          <td valign="middle"><input type="text" id="submitValue"
            style="width:20em;"></td>
          <td valign="middle"><input type="submit" value="OK"></td>
        </tr>
      </table>
    </form>
    
    <p><b>Your last three phrases were:</b>
    
    <p><span id="status">&nbsp;</span>
    
    <p><i>This page uses Gears to record your entries on the local disk.
       If you navigate away and revisit this page, all your data will still
       be here.  Try it!</i>
    
    <!-- ====================================== -->
    <!-- End HTML code.  Begin JavaScript code. -->
    
    <script type="text/javascript"  src="gears_init.js"></script>
    <script type="text/javascript" src="sample.js"></script>
    <script type="text/javascript" src="hello_world.js">
    </script>
    
    </body>
    </html>
    
  2. The hello_world.js:
    var db;
    init();
    
    // Open this page's local database.
    function init() {
      var success = false;
    
      if (window.google && google.gears) {
        try {
          db = google.gears.factory.create('beta.database');
    
          if (db) {
            db.open('database-demo');
            db.execute('create table if not exists Demo' +
                       ' (Phrase varchar(255), Timestamp int)');
    
            success = true;
            // Initialize the UI at startup.
            displayRecentPhrases();
          }
    
        } catch (ex) {
          setError('Could not create database: ' + ex.message);
        }
      }
    
      // Enable or disable UI elements
    
      var inputs = document.forms[0].elements;
      for (var i = 0, el; el = inputs[i]; i++) {
        el.disabled = !success;
      }
    
    }
    
    function handleSubmit() {
      if (!google.gears.factory || !db) {
        return;
      }
    
      var elm = getElementById('submitValue');
      var phrase = elm.value;
      var currTime = new Date().getTime();
    
      // Insert the new item.
      // The Gears database automatically escapes/unescapes inserted values.
      db.execute('insert into Demo values (?, ?)', [phrase, currTime]);
    
      // Update the UI.
      elm.value = '';
      displayRecentPhrases();
    }
    
    
    function displayRecentPhrases() {
      var recentPhrases = ['', '', ''];
    
      // Get the 3 most recent entries. Delete any others.
      var rs = db.execute('select * from Demo order by Timestamp desc');
      var index = 0;
      while (rs.isValidRow()) {
        if (index < 3) {
          recentPhrases[index] = rs.field(0);
        } else {
          db.execute('delete from Demo where Timestamp=?', [rs.field(1)]);
        }
        ++index;
        rs.next();
      }
      rs.close();
    
      var status = getElementById('status');
      status.innerHTML = '';
      for (var i = 0; i < recentPhrases.length; ++i) {
        var id = 'phrase' + i;
        status.innerHTML += '<span id="' + id + '"></span><br>';
        var bullet = '(' + (i + 1) + ') ';
        setTextContent(getElementById(id), bullet + recentPhrases[i]);
      }
    }
    
  3. The sample.js:
    function isDefined(type) {
      return (type != 'undefined' && type != 'unknown');
    }
    
    function childNodes(element) {
      if (isDefined(typeof element.childNodes)) {
        return element.childNodes;
      } else if (isDefined(typeof element.children)) {
        return element.children;
      }
    }
    
    function getElementById(element_name) {
      if (isDefined(typeof document.getElementById)) {
        return document.getElementById(element_name);
      } else if(typeof isDefined(document.all)) {
        return document.all[element_name];
      }
    }
    
    function setTextContent(elem, content) {
      if (isDefined(typeof elem.innerText)) {
        elem.innerText = content; 
      } else if (isDefined(typeof elem.textContent)) {
        elem.textContent = content;
      }
    }
    
    function setupSample() {
      // Make sure we have Gears. If not, tell the user.
      if (!window.google || !google.gears) {
        if (confirm("This demo requires Gears to be installed. Install now?")) {
          // Use an absolute URL to allow this to work when run from a local file.
          location.href = "http://code.google.com/apis/gears/install.html";
          return;
        }
      }
    
      var viewSourceElem = getElementById("view-source");
      if (!viewSourceElem) {
        return;
      }
      var elm;
      if (navigator.product == "Gecko") {
        // If we're gecko, we can show the source of the application with the
        // view-source protocol.
        elm = "<a href='view-source:" + location.href + "'>" +
              "View Demo Source" +
              "</a>";
      } else {
        // Otherwise, just tell users how to do it manually.
        elm = "<em>" +
              "To see how this works, use the <strong>view " +
              "source</strong> feature of your browser" +
              "</em>";
      }
      viewSourceElem.innerHTML += elm;
    }
    
    function checkProtocol() {
      if (location.protocol.indexOf('http') != 0) {
        setError('This sample must be hosted on an HTTP server');
        return false;
      } else {
        return true;
      }
    }
    
    function addStatus(message, opt_class) {
      var elm = getElementById('status');
      var id = 'statusEntry' + (childNodes(elm).length + 1);
      if (!elm) return;
      if (opt_class) {
        elm.innerHTML += '<span id="' + id + '" class="' + opt_class + '"></span>';
      } else {
        elm.innerHTML += '<span id="' + id + '"></span>';
      }
      elm.innerHTML += '<br>';
      setTextContent(getElementById(id), message);
    }
    
    function clearStatus() {
      var elm = getElementById('status');
      elm.innerHTML = '';
    }
    
    function setError(s) {
      clearStatus();
      addStatus(s, 'error');
    }
    
    setupSample();
    

José M. Vidal .

6 of 20