Created
December 18, 2018 03:48
-
-
Save Anenth/761665ae1160286275672331da7c67b1 to your computer and use it in GitHub Desktop.
A simple pub/sub model - `set data()` - whenever this.data is changed the `set data()` gets called
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
function Store(initialData, options = {}) { | |
const handlers = []; | |
let nextHandlerId = 0; | |
return { | |
get data() { | |
return initialData; | |
}, | |
set data(t) { | |
console.log("Set was called"); | |
handlers.forEach(handler => { | |
handler.handler(t); | |
}); | |
}, | |
set hoo(t) { | |
console.log("Set hoo was called"); | |
handlers.forEach(handler => { | |
handler.handler(t); | |
}); | |
}, | |
watch(cb) { | |
let ID = nextHandlerId++; | |
handlers.push({ | |
id: ID, | |
handler: cb | |
}); | |
return ID; | |
}, | |
unwatch(id) { | |
for (let i = 0; i < handlers.length; i++) { | |
if (handlers[i].id === id) { | |
handlers.splice(i, 1); | |
break; | |
} | |
} | |
} | |
}; | |
} | |
const TestStore = (function() { | |
const store = Store(0); | |
store.increment = function() { | |
this.data = this.data + 1; | |
}; | |
store.bla = function() { | |
this.hoo = "bo"; | |
}; | |
return store; | |
})(); | |
TestStore.watch(counter => { | |
console.log("------>", counter); | |
}); | |
TestStore.bla(); | |
TestStore.increment(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment