Skip to content

Instantly share code, notes, and snippets.

@seamusjr
Created April 22, 2015 18:43
Show Gist options
  • Save seamusjr/d0b5e7df1d290fbbdd88 to your computer and use it in GitHub Desktop.
Save seamusjr/d0b5e7df1d290fbbdd88 to your computer and use it in GitHub Desktop.
Pubsub AJAX example from Javascript Design Patterns book by Addy Osmani
<!doctype html>
<html>
<head>
<title>Publish Subscribe example</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<form id="flickrSearch">
<input type="text" name="tag" id="query"/>
<input type="submit" name="submit" value="submit"/>
</form>
<div id="lastQuery"></div>
<ol id="searchResults"></ol>
<script id="resultTemplate" type="text/html">
<% _.each(items, function( item ){ %>
<li><img src="<%= item.media.m %>"/></li>
<% });%>
</script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>
<script>
/*
* jQuery Tiny Pub/Sub
* https://github.com/cowboy/jquery-tiny-pubsub
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
*/
(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 ));
(function( $ ) {
// Pre-compile template and "cache" it using closure
var resultTemplate = _.template($( "#resultTemplate" ).html());
// Subscribe to the new search tags topic
$.subscribe( "/search/tags", function( e, tags ) {
$( "#lastQuery" )
.html("<p>Searched for:<strong>" + tags + "</strong></p>");
});
// Subscribe to the new results topic
$.subscribe( "/search/resultSet", function( e, results ){
$( "#searchResults" ).empty().append(resultTemplate( results ));
});
// Submit a search query and publish tags on the /search/tags topic
$( "#flickrSearch" ).submit( function( e ) {
e.preventDefault();
var tags = $(this).find( "#query").val();
if ( !tags ){
return;
}
$.publish( "/search/tags", [ $.trim(tags) ]);
});
// Subscribe to new tags being published and perform
// a search query using them. Once data has returned
// publish this data for the rest of the application
// to consume
$.subscribe("/search/tags", function( e, tags ) {
$.getJSON( "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: tags,
tagmode: "any",
format: "json"
},
function( data ){
if( !data.items.length ) {
return;
}
$.publish( "/search/resultSet", { items: data.items } );
});
});
})( jQuery );
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment