Created
April 6, 2012 11:16
-
-
Save mihaipaun/2318942 to your computer and use it in GitHub Desktop.
JavaScript: PubSub model for jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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