Skip to content

Instantly share code, notes, and snippets.

@uchcode
Last active July 18, 2016 12:48
Show Gist options
  • Save uchcode/84d96ea917ead83dddde59553f766680 to your computer and use it in GitHub Desktop.
Save uchcode/84d96ea917ead83dddde59553f766680 to your computer and use it in GitHub Desktop.
Application( Model, View ) pattern
'use strict';
class Model {
constructor() {
this.name = 'John';
}
}
class View {
render(id, contents) {
let element = document.getElementById(id);
element.innerHTML = contents.template;
if (contents.connect) {
let button = element.getElementsByTagName('button');
if (button.length) contents.connect(button[0]);
}
}
init(action) {
return {
template:`
<p>Ready?</p>
<button>Go</button>
`,
connect: element => {
element.addEventListener('click', () => {
action.hello();
return false;
});
}
};
}
hello(action, data) {
return {
template:`
<p>hello ${data.name}!</p>
<button>Reset</button>
`,
connect: element => {
element.addEventListener('click', () => {
action.init();
return false;
});
}
};
}
}
class Application {
constructor(args) {
let { model, view, elementId } = args||{};
this.model = model || new Model();
this.view = view || new View();
this.elementId = elementId || 'viewport';
}
init() {
let { view, elementId } = this;
view.render( elementId, view['init'](this) );
}
hello() {
let { model, view, elementId } = this;
view.render( elementId, view.hello(this, { name: model.name }) );
}
}
let app = new Application();
app.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment