Skip to content

Instantly share code, notes, and snippets.

@Anenth
Created December 18, 2018 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anenth/761665ae1160286275672331da7c67b1 to your computer and use it in GitHub Desktop.
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
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