Skip to content

Instantly share code, notes, and snippets.

@cassiano-gists
Created November 24, 2012 21:08
Show Gist options
  • Save cassiano-gists/4141404 to your computer and use it in GitHub Desktop.
Save cassiano-gists/4141404 to your computer and use it in GitHub Desktop.
JS: PubSub Paul Irish
// 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");
});
@jhagege
Copy link

jhagege commented Mar 11, 2015

Hey thanks for that.
I'm trying to learn Jquery in more depth and I'm not sure I understand the following syntax:

var o = $( {} );
$.subscribe = o.on.bind(o);

Any chance you could explain it shortly?

The on function that I know is $("#smthg").on('click', function(){});

Thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment