Skip to content

Instantly share code, notes, and snippets.

@webcss
Last active October 6, 2016 17:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webcss/86e3b0a999853370f5be to your computer and use it in GitHub Desktop.
Save webcss/86e3b0a999853370f5be to your computer and use it in GitHub Desktop.
Firebase.com with Mithril - the functional way
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 });
@webcss
Copy link
Author

webcss commented Mar 29, 2015

Changed to m.redraw() over start / end Computation since the latter is said to block the redraw cycle when invoked from subcomponents.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment