如何利用dojo / topic跨帧进行通信

时间:2014-08-19 20:58:53

标签: iframe dojo

我已经在传统的AMD前Dojo中实现了这个功能。现在我已经采用了“现代”的Dojo理念和思维方式,并且正在转换我的应用程序,我遇到了一些实际的障碍。

我的问题特定于组织dojo/topic的交叉iframe使用的首选方式 - 接管dojo.publish和订阅的新类。

在我的基本用例中,我有2个简单的网页在同一个域上运行dojo 1.10,并希望他们对广播作出反应。什么是“正确”和现代的方式来做这件事,而没有回归到旧的道场。*风格或污点全球化 - 因为这将打破咒语Kitson Kelly preached on his article

应该有干净的方法来实现这一点,那么Dojo的官方演示是如何使用dojo/topic进行帧间通信的?

1 个答案:

答案 0 :(得分:0)

据我所知,在dojo中没有办法在两个不同的框架中处理pub / sub。

所以解决方案(我实际上是在我的项目中使用它)可能是使用HTML5 Window.postMessage()在帧之间传递消息。

它可以按以下方式工作(伪代码):

示例:从要发布到第B帧的第A帧:

因此,在框架A中订阅主题,这些主题在框架a:

中的代码中以框架b为例
// listen to topics in frame a which should be sent to frame b
topic.subscribe('frameb/event', function(data){
    // actually send a message to frame b
    otherWindow.postMessage(data, '*');
});
// publish topic towards frame b
topic.publish('frameb/event', { identification: 'frameb/event', data: {}'});

在第B栏:

// listen to messages from frame a
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  // republish your message as topic using the property identification within frame b
  topic.publish(event.data.identification, event.data.data);
}
// subscribe to topic which was originally sending by frame a
topic.subscribe('frameb/event', function(data){
   // do smt
});