1 | /*
|
2 | * Copyright 2012 the original author or authors
|
3 | * @license MIT, see LICENSE.txt for details
|
4 | *
|
5 | * @author Scott Andrews
|
6 | */
|
7 |
|
8 | (function (define) {
|
9 | ;
|
10 |
|
11 | define(function (/* require */) {
|
12 |
|
13 | // A poor man's pub-sub. A single listener is supported per topic. When
|
14 | // the topic is published, the listener is unsubscribed.
|
15 |
|
16 | var topics = {};
|
17 |
|
18 | /**
|
19 | * Publishes the message to the topic, invoking the listener.
|
20 | *
|
21 | * The listener is unsubscribed from the topic after receiving a message.
|
22 | *
|
23 | * @param {string} topic the topic to publish to
|
24 | * @param {Object} message message to publish
|
25 | */
|
26 | function publish(topic /* , message... */) {
|
27 | if (!topics[topic]) { return; }
|
28 | topics[topic].apply({}, Array.prototype.slice.call(arguments, 1));
|
29 | // auto cleanup
|
30 | delete topics[topic];
|
31 | }
|
32 |
|
33 | /**
|
34 | * Register a callback function to receive notification of a message published to the topic.
|
35 | *
|
36 | * Any existing callback for the topic will be unsubscribed.
|
37 | *
|
38 | * @param {string} topic the topic to listen on
|
39 | * @param {Function} callback the callback to receive the message published to the topic
|
40 | */
|
41 | function subscribe(topic, callback) {
|
42 | topics[topic] = callback;
|
43 | }
|
44 |
|
45 | return {
|
46 | publish: publish,
|
47 | subscribe: subscribe
|
48 | };
|
49 |
|
50 | });
|
51 |
|
52 | }(
|
53 | typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }
|
54 | // Boilerplate for AMD and Node
|
55 | ));
|