Skip to content

Instantly share code, notes, and snippets.

@mihaipaun
Created April 6, 2012 11:16
Show Gist options
  • Save mihaipaun/2318942 to your computer and use it in GitHub Desktop.
Save mihaipaun/2318942 to your computer and use it in GitHub Desktop.
JavaScript: PubSub model for jQuery
/* Inspired from http://tutsplus.com/lesson/custom-events-and-the-observer-pattern/ */
(function( $ ) {
var o = $( {} );
$.each({
trigger: 'publish',
on: 'subscribe',
off: 'unsubscribe'
}, function( key, val ) {
jQuery[val] = function() {
o[key].apply( o, arguments);
};
});
})( jQuery );
/* Usage */
$.getJSON('http:/search.twitter.com/search.json?q=dogs&callback=?', function( results ) {
$.publish( 'twitter/results', results );
});
// ...
$.subscribe( 'twitter/results', function( e, results ) {
// console.log(results);
$('body').html(
$.map( results.results, function( obj, index ) {
return '<li>' + obj.text + '</li>';
}).join('')
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment