Blog
Tutorial (basic learning) » 11.HTML5 API

11.HTML5 API

Last modified by kashi on 2015/01/30, 13:10

Overview

This chapter describes a group of wrapper functions that are targeted for HTML5 API ease of use at development and execution time.

Geolocation API wrapper

Geolocation API is an API that retrieves location information.
In hifive, for easy testing of this function at development time, a feature that returns dummy location is added.
Besides, you should used h5.dev.js (containing development support functions) instead of h5.js.

html

<!doctype html>  
<html>  
<head>  
 <script src="jquery.js"></script>  
 <script src="ejs-1.0.h5mod.js"></script>  
 <script src="h5.dev.js"></script>  
</head>  
<body>  
</body>  
</html>  

Setting dummy coordinates for current location.

You can set dummy coordinates for current location to h5.dev.api.geo.dummyPositions.

h5.dev.api.geo.dummyPositions = { coords: {latitude: 35.68505914147349,longitude: 139.76440876196284}};  
  
// Dummy coordinates are returned and passed to parameter.  
h5.api.geolocation.getCurrentPosition(function(pos) {  
   var lat = pos.coords.latitude, lng = pos.coords.longitude;  
    console.log(lat +", "+ lng); // 35.68505914147349, 139.76440876196284  
});  

Setting dummy coordinates when moving

By setting interval time for value to be returned to h5.dev.api.geo.watchIntervalTime,
and dummy coordinate array to h5.dev.api.geo.dummyPositions,
dummy coordinates can be retrieved when moving along a route.

h5.dev.api.geo.watchIntervalTime = 1000;  
// Set dummy coordinates array   
h5.dev.api.geo.dummyPosition =  [{  
        latitude: 35.67920288784219,  
        longitude: 139.7650095767821  
    }, {  
        latitude: 35.68540771444479,  
        longitude: 139.7660395450439  
    }, {  
        latitude: 35.69802503048958,  
        longitude: 139.7729918308105  
    }];  
  
// Return dummy coordinates configured in h5.dev.api.geo.setDummyWatchPosition method every 1000ms
h5.api.geolocation.watchPosition().progress(function(pos) {  
   var lat = pos.coords.latitude, lng = pos.coords.longitude;  
    console.log(lat +", "+ lng);  
});

 

Forcing error

Force getCurrentPosition/watchPosition error callback to be executed.

h5.dev.api.geo.isForceError = true;  
  
h5.api.geolocation.watchPosition.progress(function(pos) {  
  
}).fail((function(error) {  
// Error callback is forced to be executed  
});  

Reference

Using dummy coordinate generation tool, you can retrieve dummy coordinates used for test purpose easily.。

Web Storage wrapper

Web Storage is a feature that stores data at client using key-value pairs.
You can use this API to temporarily store data by assigning it to a key.
Besides, local storage API is currently supported by multiple common browsers (IE (8 or later), Chrome, FireFox, Safari, Opera).
However,
standard Web Storage API can only store string value.
Although it can store data by converting object to JSON,
it cannot maintain (store or take out), for e.g, Date and RegExp (regular expression) data types.

Using hifive API enables you maintain such data types.   

  • setItem(key, value) method determines the value type and saves type information as string to storage.
    h5.api.storage.local.setItem
    h5.api.storage.session.setItem
    getItem(key) method converts the string being saved in the storage to appropriate data type and returns.
    h5.api.storage.local.getItem
    h5.api.storage.session.getItem
    An object contained in another object (nested object) is also correctly converted.

Sample code

h5.api.storage.local.setItem('key3', [10, 'AAA']);  
  
var item = h5.api.storage.local.getItem('key3'); // Able to retrieve object of Array type  
console.log(item)  
console.log(item[1]); // AAA  

Reference

Web SQL Database Wrapper

  • Working on Web SQL Database specifications has been ceased from 2010/11/18, however, it is now supported in Chrome and Safari.
  • Currently, Indexed Database specifications is being worked on as an alternative to Web SQL Database.
  • Depending on data structure, use this API if you want to query stored data via specifying a condition (for e.g, WHERE).

hifive SQL Database API is similar to a builder pattern. It generates SQL execution object after database is opened.
After configuring WHERE and ORDERBY information to SQL execution object, call execute() to run SQL queries.
Result will be returned by jQuery.Deferrd Promise object.

Sample code

// Open database  
var db = h5.api.sqldb.open('db1', '1.0', 'db1', 1024*1024);  
// Generate SQL execution object  
var select = db.select('TABLE1', ['COLUMN1','COLUMN3']).where({'COLUMN2 !=': 'AAAA'});  
// Promise object    
var promise = select.execute(); // Run SQL  
  
// Get result from Promise object  
promise.done(function(resultset) {  
    // Transaction completed  
}).fail(function(error) {  
    // Transaction failed  
}).progress(function(resultset, tx) {  
  // Continue to run SQL in the same transaction  
  var del = db.del('TABLE1' tx);  
   del.where({COLUMN1: 'suzuki').execute().done(function(deleteCount) {  
       alert(deleteCount);
   });  
}); 

Performing CRUD operations on a single table

SELECT

Example: get records where AGE > 20 from MEMBER table

  • Using SQL Database API:
var conn = openDatabase('db1', '1.0', 'db1', 1024*1024);

conn.transaction(function(tx) {
    tx.executeSql('SELECT NAME, BIRTHDAY FROM MEMBER WHERE AGE >= ?', [20], function(rs) {  
       var result = rs.rows;  
       for (var i = 0, len = result.length; i < len; i++) {  
       var row = result.item(i);  
        alert(row.NAME +', '+ row.BIRTHDAY);  
    });
});

*Using hifive API:

var db = h5.api.sqldb.open('db1', '1.0', 'db1', 1024*1024);  

db.select('MEMBER', ['NAME','BIRTHDAY']).where({'AGE >=': 20}).execute().done(function(rowItems) {  
   for (var i = 0, len = rowItems.length; i < len; i++) {  
       var row = rowItems.item(i);  
        alert(row.NAME +', '+ row.BIRTHDAY);
    }  
});  

INSERT

Example: add (NAME="tanaka" BIRTH="1990/1/1" AGE=30) record to MEMBER table

  • Using SQL Database API:
var conn = openDatabase('db1', '1.0', 'db1', 1024*1024);

conn.transaction(function(tx) {
    tx.executeSql('INSERT INTO MEMBER VALUES (?, ?, ?)', ['tanaka', '1990/1/1', 30], function(rs) {  
        alert(rs.insertId); // record ID      
   });
});
  • Using hifive API:
var db = h5.api.sqldb.open('db1', '1.0', 'db1', 1024*1024);  

db.insert('MEMBER', {NAME:'tanaka', BIRTH:'1990/1/1', AGE:30}).execute().done(function(insertIds) {  
    alert(insertIds[0]); // record ID  
});  

UPDATE

Example: update records where AGE = 30 in MEMBER table

  • Using SQL Database API:
var conn = openDatabase('db1', '1.0', 'db1', 1024*1024);

conn.transaction(function(tx) {
    tx.executeSql('UPDATE MEMBER SET NAME = ?, BIRTH = ? WHERE AGE = ?', ['suzuki', '1980/2/1', 30], function(rs) {  
        alert(rs.rowsAffected);  // Number of updated rows
   });
});
  • Using hifive API:
var db = h5.api.sqldb.open('db1', '1.0', 'db1', 1024*1024);  

db.update('MEMBER', {NAME:'suzuki', BIRTH:'1980/2/1'}).where({'AGE >=': 30}).execute().done(function(updateCount) {  
    alert(updateCount);  // Number of updated rows   
});  

DELETE

Example: delete records where AGE != 30 from MEMBER table

  • Using SQL Database API:
var conn = openDatabase('db1', '1.0', 'db1', 1024*1024);

conn.transaction(function(tx) {
    tx.executeSql('DELETE FROM MEMBER WHEREE AGE != ?', [30], function(rs) {  
        alert(rs.rowsAffected); // Number of deleted rows  
   });
});
  • Using hifive API:
var db = h5.api.sqldb.open('db1', '1.0', 'db1', 1024*1024);  

db.del('MEMBER').where({'AGE !=': 30}).execute().done(function(deleteCount) {  
    alert(deleteCount) // Number of deleted rows  
});  

Executing multiple SQLs in a single transaction.

hifive features Transaction class that executes multiple SQL in a single transaction. By adding execution SQL object to add() method of this class, after running SQLs in the added order, results can be collected and retrieved.

Example) Query TABLE1, TABLE2, TABLE3 in a single transaction.

  • Using SQL Database API:
var conn = openDatabase('db1', '1.0', 'db1', 1024*1024);
var results = [];

conn.transaction(function(tx) {
    tx.executeSql('SELECT COLUMN1, COLUMN2 FROM TABLE1 WHERE COLUMN2 != "AAA"', [], function(tx, rs) {
        results.push(rs.rows);
       
        tx2.executeSql('SELECT COLUMN3, COLUMN4 FROM TABLE2', [], function(tx2, rs2) {
            results.push(rs2.rows);
       
            tx3.executeSql('SELECT * FROM TABLE3', [], function(tx3, rs3) {
                results.push(rs3.rows);            
           });  
        });    
    });
}, function() {}, function() {
   // All transactions completed
   // Query results will be stored in "results" array in TABLE1, TABLE2, TABLE3 order
});
  • Using hifive API:
var db = h5.api.sqldb.open('db1', '1.0', 'db1', 1024*1024);  
var select1 = db.select('TABLE1', ['COLUMN1','COLUMN3']).where({'COLUMN2 !=': 'AAAA'});  
var select2 = db.select('TABLE2', ['COLUMN2','COLUMN4']);  
var select3 = db.select('TABLE3', '*').where({'COLUMN1 >=': 100});  
  
db.transaction().add(select1).add(select2).add(select3).execute().done(function(results) {  
   // All transactions completed
   // Query results will be stored in "results" array in TABLE1, TABLE2, TABLE3 order
});  

Running multiple SQLs using SQL Database API will make callback function nested, therefore code would become messy.
Using hifive API, callback function is executed in Deferred.done(), thus code readability is not affected.

Reference

Next Chapter⇒12. How to apply AOP


Copyright (C) 2012-2017 NS Solutions Corporation, All Rights Reserved.