Skip to content

Instantly share code, notes, and snippets.

@jgxvx
Created March 4, 2012 12:36
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 jgxvx/1972816 to your computer and use it in GitHub Desktop.
Save jgxvx/1972816 to your computer and use it in GitHub Desktop.
A short example on how jQuery's pubsub can be used.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="../lib/jquery.js" type="text/javascript"></script>
<script src="../lib/pubsub.js" type="text/javascript"></script>
<style type="text/css">
body {
font-family: Helvetica;
font-size: 12px;
color: #999;
}
div {
display: block;
width: 200px;
text-align: center;
border: 1px solid #999;
padding: 10px;
margin: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="publisher">publisher</div>
<div id="subscriber1" class="subscribers">subscriber 1</div>
<div id="subscriber2" class="subscribers">subscriber 2</div>
<div id="subscriber3" class="subscribers">subscriber 3</div>
<script type="text/javascript">
var Subscriber = function(el,price) {
var _element = null,
_name = null,
_price = 0,
_onCustomEvent = function(data) {
_element.html(_price += data.price);
},
_init = function() {
_element = el;
_name = el.get(0).id;
_price = price;
$.subscribe('customEvent',function(data){
_onCustomEvent(data);
});
}();
this.getElement = function() {
return _element;
};
this.getName = function() {
return _name;
};
this.getPrice = function() {
return _price;
};
};
var subscriber1 = new Subscriber($('#subscriber1'),100);
var subscriber2 = new Subscriber($('#subscriber2'),200);
var subscriber3 = new Subscriber($('#subscriber3'),300);
$(document).ready(function(){
$('#publisher').click(function(e){
$.publish('customEvent',[{'price':200}]);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment