Skip to content

Instantly share code, notes, and snippets.

@bhalash
Last active May 4, 2016 13:39
Show Gist options
  • Select an option

  • Save bhalash/d72b9645da8e0f539e85a2387bd01484 to your computer and use it in GitHub Desktop.

Select an option

Save bhalash/d72b9645da8e0f539e85a2387bd01484 to your computer and use it in GitHub Desktop.
Super-simple explanation of jQuery's pub/sub model
/**
* Super-duper simple explanation of jQuery's pub/sub model.
* See: https://gist.github.com/cowboy/661855
* See: https://github.com/cowboy/jquery-tiny-pubsub
*/
/*
* 1. Pass DOM element to jQuery and save the instance as a variable.
*/
var $body = $('body');
/*
* 2. Attach click event.
*/
$body.on('click', function() {
console.log($.now() + ': The body of the document was clicked!');
});
$body.trigger('click'); // '1461922847625: The body of the document was clicked!'
/*
* 3. Objects can also be passed through jQuery.
*/
var $observer = $({});
/*
* 4. Custom events can be bound to the event. Events are namespaced
* and separated by a forward slash (/).
*/
$observer.on('/magic/horse/fart', function(event, message) {
console.log($.now() + ': A magic horse farted!' + ' ' + message);
});
$body.on('click', function() {
$observer.trigger('/magic/horse/fart', 'Neighhhh!'); // '1461922848625: A magic horse farted! Neighhh!'
});
$body.off('click');
/*
* 5. Custom functions can be added to jQuery which manipulate the observer.
*
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
* See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments
*/
$.publish = function() {
$observer.trigger.apply($observer, arguments);
}
$.subscribe = function() {
$observer.on.apply($observer, arguments);
}
/*
* 6. Example subscribe/publish.
*/
$.subscribe('/magic/pony/fart', function(event, message) {
console.log(message);
});
$body.on('click', function() {
$.publish('/magic/pony/fart', 'A magic horse farted!'); // 1461922848625: 'A magic horse farted!'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment