阿里云赞助

JS Framework APIs

JS Framework APIs

BroadcastChannel v0.9+

BroadcastChannel API is the solution for inter-instance communication.

Reference

API

  • postMessage(message): Sends the given message to other BroadcastChannel objects set up for this channel.
  • close: Closes the BroadcastChannel object, opening it up to garbage collection.
  • onmessage: Event handler, the event will be triggered when the instance receive a message.

Usage

const Stack = new BroadcastChannel('Avengers')
Stack.onmessage = function (event) {
console.log(event.data) // in this case, it's "Hulk Smash !!!"
}
// in another instance
const Hulk = new BroadcastChannel('Avengers')
Hulk.postMessage("Hulk Smash !!!")

Run the code above, Stack can receive the message from Hulk.

Notice

One thing should be noticed: The message object is not deep cloned.

See the demo below:

const a = new BroadcastChannel('app')
const b = new BroadcastChannel('app')
const message = {
lists: ['A', 'B']
}
a.onmessage = function (event) {
// in this case, event.data is a reference of message
console.assert(event.data === message)
}
b.postMessage(message)

In this case, event.data is strict equal to message.

Compared to the deep clone, this behavior improves efficiency and reduces memory cost. However, developers are not recommended to cache or modify the event object when they are using it (All type of event handlers should have this restriction).

Apache Incubator
Disclaimer: Apache Weex is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Apache Incubator. Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.


ApacheCopyright(c) 2017 The Apache Software Foundation. Licensed under the Apache License, Version 2.0