Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple pub/sub model - `set data()` - whenever this.data is changed the `set data()` gets called
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