Skip to content

Instantly share code, notes, and snippets.

@dearshrewdwit
Created December 14, 2018 11:57
Show Gist options
  • Select an option

  • Save dearshrewdwit/1d1adaa64502f9ddd43f25e39131b86e to your computer and use it in GitHub Desktop.

Select an option

Save dearshrewdwit/1d1adaa64502f9ddd43f25e39131b86e to your computer and use it in GitHub Desktop.
An MVP exemplar of a notes SPA
// /app.js
// on load, create the controller, render the initial list view
window.addEventListener('load', function() {
// create a note-list-model, with a Note
var noteList = new NoteList(Note)
// create the note-list-view
var noteListView = new NoteListView(noteList)
var controller = new NotesController(noteList, noteListView, NoteView)
// render the list view
var html = noteListView.render()
controller.render(html)
})
// src/notes-controller.js
function NotesController(noteList, noteListView, noteView) {
this.noteList = noteList
this.noteListView = noteListView
this.NoteView = noteView
this._setup()
}
NotesController.prototype = {
_setup: function() {
var self = this
// listen to submit events
window.addEventListener('submit', function(event) {
// stop the default, ask the list to create a note, and then render
event.preventDefault()
self.noteList.createNote(event.target[0].value)
var html = self.noteListView.render()
self.render(html)
})
window.addEventListener('hashchange', function() {
// get the hash location
// find the id
var noteId = window.location.hash.split('#notes/')[1]
// find the note from notelist
var note = self.noteList.findById(noteId)
// create a note-view
var noteView = new self.NoteView(note)
// render the note-view
var html = noteView.render()
self.render(html)
})
},
render: function(html) {
document.getElementById('app').innerHTML = html
}
}
// src/note-list-model.js
function NoteList(noteModel) {
this.noteModel = noteModel
this.notes = []
}
NoteList.prototype = {
createNote: function(text) {
var note = new this.noteModel(text)
this.notes.push(note)
},
findById: function(id) {
return this.notes.find(function(note) {
return note.id == id
})
}
}
// src/note-model.js
(function(exports) {
var id = 0
function Note(text) {
this.text = text
id++
this.id = id;
}
Note.prototype = {
title: function() {
return this.text.substring(0, 20)
}
}
exports.Note = Note
})(this)
// src/note-list-view.js
function NoteListView(noteList) {
this.noteList = noteList
}
NoteListView.prototype = {
render: function() {
return [
"<form>",
"<input type='text'></input>",
"<input type='submit'></input>",
"</form>",
this.noteList.notes.map(function(note) {
return [
"<div>",
"<a href='#notes/" + note.id + "'>" + note.title() + "</a>",
"</div>"
].join('')
}).join('')
].join('')
}
}
// src/note-view.js
function NoteView(note) {
this.note = note
}
NoteView.prototype = {
render: function() {
return [
"<div>",
"<p>" + this.note.text + "</p>",
"</div>"
].join('')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment