-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.js
82 lines (73 loc) · 2.7 KB
/
pubsub.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// Atto PubSub : Just another lightweight Pub/Sub module
// based loosely on:
// Addy Osmani's pubsubz: https://github.com/addyosmani/pubsubz/blob/master/pubsubz.js
// and
// Peter Higgins' bloody jQuery plugns: https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
//
// author: Ryan Corradini
// version: 1.0
// date: 22 June 2012
// license: MIT
//
define(
function() {
// private defs & methods
var topic_cache = {},
lastUid = -1;
/**
* Publish the specified topic, passing the provided data to all subscriber callbacks
* @topic: The topic to publish
* @data: The data to pass to subscribers
**/
function _pub( topic, data ){
var subscribers = topic_cache[topic],
len = subscribers && subscribers.length ? subscribers.length : 0;
setTimeout(function notify(){
while( len-- ){
subscribers[len].func( topic, data || [] );
}
}, 0 );
return true;
};
/**
* Add the passed callback function to the subscriber list for the provided topic.
* Returns: Unique subscription ID, which can be used to unsubscribe
* @topic: The topic to subscribe to
* @callback: The callback function to invoke when the provided topic is published
**/
function _sub( topic, callback ){
// init subscriber list for this topic if necessary
if ( !topic_cache.hasOwnProperty( topic ) ){
topic_cache[topic] = [];
}
var id = (++lastUid).toString();
topic_cache[topic].push( { id : id, func : callback } );
// return ID for unsubscribing
return id;
};
/**
* Unsubscribes a specific subscriber from a specific topic using the unique ID
* @id: The ID of the function to unsubscribe
**/
function _unsub( id ){
for ( var m in topic_cache ){
if ( topic_cache.hasOwnProperty( m ) ){
for ( var i = 0, j = topic_cache[m].length; i < j; i++ ){
if ( topic_cache[m][i].id === id ){
topic_cache[m].splice( i, 1 );
return true;
}
}
}
}
return false;
};
// public interface
return {
publish : _pub,
subscribe : _sub,
unsubscribe : _unsub
} // end of public interface
}
); // end of atto/pubsub