Skip to content

Instantly share code, notes, and snippets.

@rgarro
Forked from dharFr/jquery.observer.js
Created May 7, 2012 18:07
Show Gist options
  • Save rgarro/2629368 to your computer and use it in GitHub Desktop.
Save rgarro/2629368 to your computer and use it in GitHub Desktop.
jQuery based observer pattern
;(function($) {
/*
* jQuery Observer pattern
* inspired by @addyosmani 's code
* see: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#highlighter_506612
*/
var topics = [];
function getTopic(id) {
var callbacks;
topic = id && topics[id];
if (!topic) {
callbacks = $.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if (id) topics[id] = topic;
}
return topic;
}
$.observer = {
publish: function(id) {
var args = (2 <= arguments.length) ? Array.prototype.slice.call(arguments, 1) : [];
var t = getTopic(id);
return t.publish.apply(t, args);
},
subscribe: function(id, fn) {
return getTopic(id).subscribe(fn);
},
unsubscribe: function(id, fn) {
return getTopic(id).unsubscribe(fn);
}
};
})(jQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>jQuery Observer Pattern Sample</title>
</head>
<body>
<p>Outputs to console...</p>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="jquery.observer.js"></script>
<script>
function fn1() { console.log('fn1 called', arguments); }
function fn2() { console.log('fn2 called', arguments); }
function fn3() { console.log('fn3 called', arguments); }
function publish() {
var args = (1 <= arguments.length) ? Array.prototype.slice.call(arguments, 0) : [];
console.group('publish ' + args[0]);
$.observer.publish.apply($.observer, args);
console.groupEnd();
}
$.observer.subscribe('test1', fn1);
$.observer.subscribe('test1', fn2);
$.observer.subscribe('test2', fn3);
publish('test1', 'strArg1', 'strArg2');
publish('test2', 1, 2, '3');
$.observer.unsubscribe('test1', fn2);
publish('test1', {key1: 'val1', key2: 'val2'});
publish('test2');
$.observer.unsubscribe('test1', fn1);
publish('test1');
publish('test2');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment