Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created April 27, 2018 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/959178a8455bb95504063cc853d80b74 to your computer and use it in GitHub Desktop.
Save Kcko/959178a8455bb95504063cc853d80b74 to your computer and use it in GitHub Desktop.
/* 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));
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Custom Events</title>
</head>
<body>
<h1>Hi There</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// PubSub
(function( $ ) {
var o = $( {} );
$.each({
trigger: 'publish',
on: 'subscribe',
off: 'unsubscribe'
}, function( key, val ) {
jQuery[val] = function() {
o[key].apply( o, arguments );
};
});
})( jQuery );
$.getJSON('http://search.twitter.com/search.json?q=dogs&callback=?', function( results) {
$.publish( 'twitter/results', results );
});
// ...
$.subscribe( 'twitter/results', function( e, results ) {
$('body').html(
$.map( results.results, function( obj, index) {
return '<li>' + obj.text + '</li>';
}).join('')
);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment