Skip to content
Advertisement

Swift/Foundation NotificationCenter equivalent in JavaScript

I’m looking for a Swift/Foundation NotificationCenter equivalent in vanilla JS.


Here’s a short explanation on what NotificationCenter is:

With NotificationCenter, you’re able to post a notification and other objects can subscribe to that notification. When the notification gets sent, a function gets invoked in the classes that subscribed. Optionally, you can also send custom user info.

Subscribing to a notification looks like this:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(fooPosted),
    name: Notification.Name("foo"),
    object: nil
)

Posting a notification looks like this:

NotificationCenter.default.post(
    name: Notification.Name("foo"),
    object: nil,
    userInfo: ["bar": 42]
)

Advertisement

Answer

Assuming client-side javascript, you can use postMessage to implement a basic pub/sub workflow:

window.addEventListener("message", e => {
  console.log('got the message', e.data)  
});

window.addEventListener("message", e => {
  console.log('me too', e.data)  
});

n = 0
function test() {
  window.postMessage('hello' + (++n))
}
<button onclick='test()'>test</button>

Alternatively, there are custom events.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement