Skip to content

Instantly share code, notes, and snippets.

@gilbert
Last active March 31, 2018 19:38
Show Gist options
  • Save gilbert/f7f88c1fe093159328a0 to your computer and use it in GitHub Desktop.
Save gilbert/f7f88c1fe093159328a0 to your computer and use it in GitHub Desktop.
Mithril-friendly Model Layer
var Comment = {}
Comment.store = Store('Comment')
Comment.fetchForPost = function (postId) {
return m.request({ method: 'GET', url: '/api/post/' + postId + '/comments' })
.then(Comment.store.syncAll)
}
Comment.update = function (attrs) {
return m.request({ method: 'PUT', url: '/api/comments/' + attrs.id, data: attrs })
.then(Comment.store.sync)
}
var PostPage = {}
PostPage.controller = function () {
Comment.fetchForPost( m.route.param('id') )
}
PostPage.view = function (ctrl) {
return Comment.store.map(function(comment) {
m('.comment', comment.text)
})
}
m.route(document.getElementById('app'), '/', {
'/posts/:id': PostPage
})
//
// A store is a "local database" of models.
// This is not persisted via localstorage, but it could be.
//
var Store = function (modelName) {
var store = {}
var api = {}
api.all = function () {
return Object.keys(store).map(function(id){ return store[id] })
}
api.map = function (callback) {
var results = []
for (var id in store) results.push( callback(store[id]) )
return results
}
api.find = function (id) {
return store[id]
}
api.findBy = function (query) {
for (var id in store) {
if ( eq(query, store[id]) ) return store[id]
}
return null
}
api.sync = function (record) {
if (! record.id) throw new Error(modelName + '.store.sync() needs a property id')
store[record.id] = record
return record
}
api.syncAll = function (records) {
return records.map(api.sync)
}
api.clear = function () {
store = {}
}
return api
}
function eq (pred, obj) {
for (var prop in pred) {
if (pred[prop] !== obj[prop]) return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment