Skip to content

Instantly share code, notes, and snippets.

@StevenMDixon
Last active July 8, 2019 18:02
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 StevenMDixon/1bfc6a9b8fb3e6959db0cfb2b8144725 to your computer and use it in GitHub Desktop.
Save StevenMDixon/1bfc6a9b8fb3e6959db0cfb2b8144725 to your computer and use it in GitHub Desktop.
Creating an MVC that works
function Observer(modelUpdate, veiwUpdate) {
this.subscribers = [];
this.subscribe = function(model, view) {
let id = this.subscribers.length;
let newModel = new model(modelUpdate.bind(this, id));
let newView = new view(veiwUpdate.bind(this, id));
this.subscribers.push({
model: newModel,
view: newView
});
this.notify(id);
}
this.notify = function(location) {
this.subscribers.forEach(function(sub, i) {
if (i === location) {
sub.view.render(sub.model.data);
}
});
}
return this;
}
function Controller() {
this.handleEvent = function(id, event, data) {
this.subscribers[id].model[event](data);
}
this.updateData = function(id, data) {
let dataKeys = Object.keys(data);
dataKeys.forEach(key => {
this.subscribers[id].model.data[key] = data[key];
});
this.notify(id);
}
this.addSubscriber = function(model, view) {
this.observer.subscribe(model, view);
}
this.observer = new Observer(this.updateData, this.handleEvent);
}
function sampleAppModel(updateData) {
this.data = {
todos: [
"test",
"run",
"test"
]
}
this.addTodo = function(data) {
if (data !== "") {
updateData({
todos: this.data.todos.concat([data])
});
}
}
this.removeTodo = function(data) {
updateData({
todos: this.data.todos.filter(function(item, index){
if (Number(data) !== index) {
return item
}
})
});
}
}
function sampleAppView(notifyEvent) {
this.render = function(data) {
document.querySelector('body').innerHTML = `
<h2>Todo List</h2>
<input id="test"></input>
<button id="btn">Add Todo</button>
<ol>${data.todos.reduce((acc, cur, index)=>{acc += `<li class="todo" data-index="${index}">${cur}</li>`; return acc}, "")}</ol>
`;
this.handleInput();
}
this.handleInput = function() {
document.querySelector('#btn').addEventListener('click', () => {
notifyEvent('addTodo', document.querySelector("#test").value);
})
todos = document.querySelectorAll('.todo');
for (let i = 0; i < todos.length; i++) {
todos[i].addEventListener('click', (e) => {
notifyEvent('removeTodo', e.target.getAttribute('data-index'));
})
}
}
}
const sampleController = new Controller();
sampleController.addSubscriber(sampleAppModel, sampleAppView);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment