Skip to content

Instantly share code, notes, and snippets.

@nordfjord
Forked from gilbert/comment-model.js
Last active November 9, 2015 18:58
Show Gist options
  • Save nordfjord/7ea72fc16b0e11de8102 to your computer and use it in GitHub Desktop.
Save nordfjord/7ea72fc16b0e11de8102 to your computer and use it in GitHub Desktop.
Mithril-friendly Model Layer
var Comment = {}
Comment.store = Store('Comment', {idprop: 'id'});
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
})
var Store = function (modelName, opts) {
opts = opts || {};
var idprop = opts.idprop || 'id';
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[idprop]) throw new Error(modelName + '.store.sync() needs a property id')
store[record[idprop]] = 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