forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubsub-custom-events.html
More file actions
67 lines (50 loc) · 1.49 KB
/
pubsub-custom-events.html
File metadata and controls
67 lines (50 loc) · 1.49 KB
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
/* Title: Custom events using .on() and .off()
* Description: A really tiny pub/sub implementation for jQuery 1.7 using the two new methods(since jQuery 1.7): .on() and .off().
*/
/* jQuery Tiny Pub/Sub - v0.7 - 10/27/2011
* http://benalman.com/
* Copyright (c) 2011 "Cowboy" Ben Alman; Licensed MIT, GPL */
(function($) {
var o = $({});
$.subscribe = function() {
o.on.apply(o, arguments);
};
$.unsubscribe = function() {
o.off.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
};
}(jQuery));
// Usage:
// Super-basic example:
function handle(e, a, b, c) {
// `e` is the event object, you probably don't care about it.
console.log(a + b + c);
};
$.subscribe("/some/topic", handle);
$.publish("/some/topic", [ "a", "b", "c" ]);
// logs: abc
$.unsubscribe("/some/topic", handle); // Unsubscribe just this handler
// Or:
$.subscribe("/some/topic", function(e, a, b, c) {
console.log(a + b + c);
});
$.publish("/some/topic", [ "a", "b", "c" ]);
// logs: abc
// Unsubscribe all handlers for this topic
$.unsubscribe("/some/topic");
// References
// https://gist.github.com/1321768
</script>
</body>
</html>