Last active
August 29, 2015 14:01
-
-
Save bfillmer/ab60f2797027c935e03c to your computer and use it in GitHub Desktop.
Generic Page Listener for Tiny PubSub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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