Skip to content

Instantly share code, notes, and snippets.

@shavit
Created December 11, 2016 20:49
Show Gist options
  • Save shavit/f05dc00ce4eb2dcd2821047befbaae56 to your computer and use it in GitHub Desktop.
Save shavit/f05dc00ce4eb2dcd2821047befbaae56 to your computer and use it in GitHub Desktop.
Publish subscribe with Javascript
class Router {
constructor(){
const path = (window.location.href.split("/#!")[1])
?(window.location.href.split("/#!")[1])
:(window.location.href.split(/src\/html/)[1])
// callbacks
this.actions = []
this.state = {
baseURL: window.location.protocol+"://"+window.location.host,
path: path,
action: (path.split("/")[1] || "index")
}
}
subscribe(callback){
let i = this.actions.push(callback)
return {
remove: () => {
delete this.actions[i-1]
}
}
}
publish(data){
this.actions.map((action) => {
action(data)
})
}
dispatch(){
console.log("dispatch")
window.onclick = (event) => {
(event.target.localName == "a")
?(event.preventDefault() && this.setAction(event))
:null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment