Created
April 22, 2015 16:25
-
-
Save seamusjr/f44be4db23380468bbc6 to your computer and use it in GitHub Desktop.
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
<!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> | |
<script id="itemTemplate" type="text/html"> | |
<li><%= name %></li> | |
</script> | |
<div id="container"> | |
<div class="sampleForm"> | |
<p> | |
<label for="item_name">Item name:</label> | |
<input type="text" id="item_name" /> | |
</p> | |
<p> | |
<button id="add">Add Item</button> | |
<button id="remove-all">Remove all</button> | |
</p> | |
</div> | |
<div class="summaryTable"> | |
<h3>Recent items</h3> | |
<ul id="items"></ul> | |
</div> | |
</div> | |
<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( $ ) { | |
var itemTemplate = _.template($( "#itemTemplate" ).html()); | |
// Subscribe to the new item topic, | |
// adds item to a list of items | |
function subscribeNewItems() { | |
$.subscribe( '/new/item', function( e, data ){ | |
if( data ) { | |
$('#items').append( itemTemplate( data )); | |
} | |
}); | |
} | |
// Handler for adding a new item | |
$('#add').on('click', function( e ) { | |
e.preventDefault(); | |
var strItem = $('#item_name').val(); | |
// Inform the application a new item is available | |
$.publish( '/new/item', { name: strItem } ); | |
}); | |
// Detach DOM elements from #items UL | |
function clearItemsList() { | |
$('#items').children('li').detach(); | |
} | |
// Remove button, unsubscribe items, clear list, rebind subscribe event | |
$('#remove-all').on('click', function( e ){ | |
e.preventDefault(); | |
$.unsubscribe('/new/item'); | |
clearItemsList(); | |
// subscribe must be rebound after unsubscribe | |
subscribeNewItems(); | |
}); | |
function init() { | |
subscribeNewItems(); | |
} | |
init(); | |
}( jQuery )); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment