分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

JS观察者设计模式:实现iframe之间快捷通信

发布时间:2023-09-06 01:13责任编辑:彭小芳关键词:暂无标签

观察者设计模式又称订阅发布模式,在JS中我们习惯叫做广播模式,当多个对象监听一个通道时,只要发布者向该通道发布命令,订阅者都可以收到该命令,然后执行响应的逻辑。今天我们要实现的就是通过观察者设计模式,实现iframe之间的通信。

一、top对象

一般的JS书里都会在讲框架集的时候讲top,这会让人误解,认为top对象只是代表框架集,其实top的含义应该是说浏览器直接包含的那一个页面对象,也就是说如果你有一个页面被其他页面以iframe的方式包含了,无论包含的层级是什么,都可以用top访问最外层的哪一个页面,因为这个页面被浏览器直接包含,这个事情的意义在于如果多个页面被同时加载,他们之间需要通信,就完全可以在最外层的页面设置一个通信对象,其他页面都通过这个对象进行通信(需要说明的是,如果要这么干,需要将他们部署在服务器上进行测试,仅仅在文件系统上测试,可能因为跨域而测试失败)。

二、搭建广播站

(function(top,undefined){var observerAble={};var radioStation={};radioStation.subscription=function(channel,obj){if(!observerAble[channel]){var array=new Array();array.push(obj);observerAble[channel]=array;}else{observerAble[channel].push(obj);}};radioStation.broadcast=function(channel,data){for(var item in observerAble[channel]){observerAble[channel][item].update(data);}};top.radioStation=radioStation;}(top))

  我们将广播站放到top对象中,后面的所有iframe都可以从top中获得该对象。我们只要建立通道,一旦广播站对该通道发布命令,我们就可以从update方法中获取命令参数。

三、测试

1、radioStation.html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script type="text/javascript" src="jquery-3.2.1.js"></script><!-- 引入广播站,创建广播站对象--><script type="text/javascript" src="RadioStation.js"></script></head><body><button id="broadcast">broadcast</button><iframe src="radioStation2.html" frameborder="0"></iframe><div id="topdiv1"></div><div id="topdiv2"></div><script>function sayHello(){this.update=function(data){$("#topdiv1").text(data);}}function sayGoodBye(){this.update=function(data){$("#topdiv2").text(data);}}var sayhello=new sayHello();var saygoodbye=new sayGoodBye();//订阅radioStation.subscription("hello",sayhello);radioStation.subscription("hello",saygoodbye);//广播$("#broadcast").click(function(){radioStation.broadcast("hello",‘hello radioStation‘);});</script></body></html>

  2、radioStation2.html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script type="text/javascript" src="jquery-3.2.1.js"></script></head><body>我是一个iframe<div id="iframediv1"></div><div id="iframediv2"></div><script>function sayHello(){this.update=function(data){$("#iframediv1").text(data);}}function sayGoodBye(){this.update=function(data){$("#iframediv2").text(data);}}var sayhello=new sayHello();var saygoodbye=new sayGoodBye();//订阅,从最外层的窗口对象top中获取radioStation对象top.radioStation.subscription("hello",sayhello);top.radioStation.subscription("hello",saygoodbye);</script></body></html>

  四、效果

JS观察者设计模式:实现iframe之间快捷通信

原文地址:http://www.cnblogs.com/iwideal/p/7587225.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved