Last active
October 6, 2016 17:10
-
-
Save webcss/86e3b0a999853370f5be to your computer and use it in GitHub Desktop.
Firebase.com with Mithril - the functional way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fireactive = function(controller) { | |
return function(args) { | |
var instance = {}; | |
var _ref = args.firebase; | |
instance.ref = _ref; | |
if (args.asObject) { | |
_ref.on('value', function asObject(snap) { | |
// m.startComputation(); | |
controller.call(instance, { data: snap.val() }); | |
// m.endComputation(); | |
m.redraw(); | |
}); | |
} else { | |
_ref.on('value', function asArray(snap) { | |
var out = []; | |
// m.startComputation(); | |
snap.forEach(function(rec) { | |
var data = rec.val(); | |
data._id = rec.key(); | |
out.push(data); | |
}); | |
controller.call(instance, { data: out }); | |
// m.endComputation(); | |
m.redraw(); | |
}); | |
} | |
instance.onunload = function() { | |
_ref.off('value'); | |
}; | |
return instance; | |
}; | |
}; | |
// usage: | |
var MyCustomers = new Firebase('https://<myfirebase>.firebaseio.com/customers') | |
var Customers = {}; | |
Customers.controller = fireactive(function(args) { | |
this.customers = args.data; | |
}); | |
Customers.view = function(ctrl) { | |
return m('ul', ctrl.customers.map(function(customer) { | |
return m('li', { key: customer._id }, customer.name ); | |
})); | |
}; | |
m.module(document.body, Customers, { firebase: MyCustomers }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changed to m.redraw() over start / end Computation since the latter is said to block the redraw cycle when invoked from subcomponents.