Last active
May 25, 2018 12:46
-
-
Save joshuakemmerling/b8e24cf71af2de7d5039 to your computer and use it in GitHub Desktop.
Vanilla pub/sub system.
This file contains hidden or 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
events.publish('/page/load', { | |
url: '/some/url/path' // any argument | |
}); | |
var subscription = events.subscribe('/page/load', function(obj) { | |
// Do something now that the event has occurred | |
}); | |
// ...sometime later where I no longer want subscription... | |
subscription.remove(); |
This file contains hidden or 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
var events = (function(){ | |
var topics = {}; | |
var hOP = topics.hasOwnProperty; | |
return { | |
subscribe: function(topic, listener) { | |
// Create the topic's object if not yet created | |
if(!hOP.call(topics, topic)) topics[topic] = []; | |
// Add the listener to queue | |
var index = topics[topic].push(listener) -1; | |
// Provide handle back for removal of topic | |
return { | |
remove: function() { | |
delete topics[topic][index]; | |
} | |
}; | |
}, | |
publish: function(topic, info) { | |
// If the topic doesn't exist, or there's no listeners in queue, just leave | |
if(!hOP.call(topics, topic)) return; | |
// Cycle through topics queue, fire! | |
topics[topic].forEach(function(item) { | |
item(info != undefined ? info : {}); | |
}); | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment