Skip to content

Instantly share code, notes, and snippets.

@bfillmer
Last active August 29, 2015 14:01
Show Gist options
  • Save bfillmer/ab60f2797027c935e03c to your computer and use it in GitHub Desktop.
Save bfillmer/ab60f2797027c935e03c to your computer and use it in GitHub Desktop.
Generic Page Listener for Tiny PubSub
/**
* Quick and simple wrapper for Tiny PubSub (https://github.com/cowboy/jquery-tiny-pubsub).
* Wanted to be able to simply update an array with various events/classes/ids to watch for
* and have a single function fired. Also leverages Underscore.js (http://underscorejs.org/).
*/
// What we want to watch for: key = event to listen for, value array = class/ids to watch for.
var eventsAndElementsToWatch = {
click: ['.btn','.link'],
change: ['.input'],
}
// Loop through events, then classes/ids, attach a listener to the document
// that matches that event/identifier that publishes to our subscription.
_.each(eventsAndElementsToWatch, function(value, key, list){
_.each(value, function(element, index, list){
$(document).on(key, element, function() {
$.publish('thingWeNeedFired', [element, key]);
});
});
});
// Function to run on publish.
var functionWeWantRun = function() {
return function(_, element, key){
console.log('What was triggered:', element);
console.log('And how!', key);
}
}
// Create subscription.
$.subscribe('thingWeNeedFired', functionWeWantRun());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment