Skip to content

Instantly share code, notes, and snippets.

@jvanja
Forked from cassiano-gists/gist:4141404
Last active August 29, 2015 14:01
Show Gist options
  • Save jvanja/31af5b0712e565755f42 to your computer and use it in GitHub Desktop.
Save jvanja/31af5b0712e565755f42 to your computer and use it in GitHub Desktop.
JavaScript: Pub/Sub
// Works in modern browsers + IE9, but Modernizr has a polyfill baked in for function.bind.
// Hat tip Paul Irish
var o = $( {} );
$.subscribe = o.on.bind(o);
$.unsubscribe = o.off.bind(o);
$.publish = o.trigger.bind(o);
// Usage
$(document.body).on( 'click', function() {
// ...yadada
$.publish( 'clicketyClack' ); // Think Rocky Balboa yelling out the window: "Hey yo!"
});
// And some dude listening patiently for Rocky's voice.
$.subscribe( 'clicketyClack', function() {
console.log("You can't win, Rock");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment