Google Gears 体验(2):本机 web 服务器

GoogleGears 的第二个官方例子:
http://code.google.com/apis/gears/samples/hello_world_resourcestore.html


这个例子的内容是演示如何在本机保存网上的资源,以便开发离线应用。

要注意的是这个离线资源是和浏览器的缓存无关的,可以拔掉网线删除浏览器缓存,这时仍然可以通过常规 URL (比如:http://code.google.com/apis/gears/samples/hello_world_resourcestore.html)访问页面的功能!

gears2.jpg

该应用的初始化阶段,需要用 js 先创建本地服务器对象:

var localServer =
        google.gears.factory.create('beta.localserver', '
1.0');


例子界面中的几个按钮功能的分析如下

1. CreateStore:    创建一个 Store。Store 之于 LocalServer,类似于数据库的 Table 之于 DataBase 的关系。

var STORE_NAME = 'helloworld-store';
// 如果该名称的 Store 已经存在,则会打开已有的。
var store = localServer.createStore(STORE_NAME);


2. Capture: 捕获需要的资源到本地。

// 先在一个数组里定义好需要获取到本机的资源名称
var filesToCapture = [
  location.pathname,  
// 代表当前页面的 url
  'sample.js',
  'sample.css',
  'gears_init.js'
];

// 捕获文件到本地,允许指定一个回调函数进行自定义的处理
store.capture(filesToCapture, captureCallback);

// 回调函数。这里仅仅做一下进展状态的汇报工作
function captureCallback(url, success, captureId) {
  addStatus(url 
+ ' captured ' + (success ? 'succeeded' : 'failed'));
}

3. UnCapture: 取消捕获

for (var i = 0; i < filesToCapture.length; i++) {
    store.remove(filesToCapture[i]);
}

4. RemoveStore: 删除 Store

// 删除 Store 之前需要首先用 openStore 方法测试其是否存在
if (localServer.openStore(STORE_NAME)) {
    localServer.removeStore(STORE_NAME);
    
// 释放 store 占用的指针,标志为可垃圾回收资源
    store = null;
}


这个例子非常简单,没有太多可说的。更多的就要去参考在线的 API 文档了。地址在:
http://code.google.com/apis/gears/api_localserver.html

原文地址:https://www.cnblogs.com/RChen/p/googlegears_2.html