Home > Web Front-end > JS Tutorial > body text

浅谈JavaScript的Polymer框架中的behaviors对象

PHPz
Release: 2018-09-29 14:14:58
Original
1700 people have browsed it

这篇文章主要介绍了浅谈JavaScript的Polymer框架中的behaviors对象,Polymer是由Google开发的Web UI相关框架,需要的朋友可以参考下

localStorage 应是家喻户晓的?但本地存储这个家族可远不止它。以前扯过 sessionStorage,现在还有个神奇的 CacheStorage。它用来存储 Response 对象的。也就是说用来对 HTTP ,响应做缓存的。虽然 localStorage 也能做,但是它可能更专业。

CacheStorage 在浏览器上的引用名叫 caches 而不是驼峰写法的 cacheStorage,它定义在 ServiceWorker 的规范中。CacheStorage 是多个 Cache 的集合,而每个 Cache 可以存储多个 Response 对象。

废话不能说再多,下面是 demo

<script>
caches.delete(&#39;c1&#39;);
caches.delete(&#39;c2&#39;);
Promise.all([
 caches.open(&#39;c1&#39;).then(function(cache) {
  return cache.put(&#39;/hehe&#39;, new Response(&#39;aaa&#39;, { status: 200 }));
 }),
 caches.open(&#39;c2&#39;).then(function(cache) {
  return cache.put(&#39;/hehe&#39;, new Response(&#39;bbb&#39;, { status: 200 }));
 })
]).then(function() {
 return caches.match(&#39;/hehe&#39;);
}).then(function(response) {
 return response.text();
}).then(function(body) {
 console.log(body);
});
</script>
Copy after login

首先,在 caches 上调用 open 方法就可以异步地得到一个 Cache 对象的引用。在这个对象上我们可以把 Response 对象 put 进去(参数是一个 URL 和一个 Response 对象)、用 match 方法取出(传入一个 URL 取出对应的 Response 对象)。

match 方法不仅可以在 Cache 上调用 CacheStorage 上也有 match 方法,比如上面例子就打开了两个 Cache,都写入一个叫 /hehe 的 URL。在写入操作完成之后,到外部的 CacheStorage 上调用 match 方法来匹配 /hehe,结果是随机的(没找到这个规则在哪里定义的)。

虽然上面的例子中只对 Cache 对象 put 了一个数据,而 Cache 对象本身可以存放更多的 URL/Response 对。并且提供了 delete(用户删除)、keys(用于遍历)等方法。但是 Cache 并不像 localStorage 一样有 clear 方法,如果非要清空一个 Cache,可以直接在 CacheStorage 上把整个 Cache 给 delete 掉再重新 open。

这套 API 和 ServiceWorker 一家的,它通常被用于 ServiceWorker 中,整个设计风格也和 ServiceWorker 一样都基于 Promise。 

以上就是本章的全部内容,更多相关教程请访问JavaScript视频教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!