Skip to content

Instantly share code, notes, and snippets.

@marshallswain
Created April 3, 2014 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marshallswain/9963824 to your computer and use it in GitHub Desktop.
Save marshallswain/9963824 to your computer and use it in GitHub Desktop.
CanJS Firebase Map. Pass in a firebase snapshot and get a can.Map that syncs with Firebase when an attribute is updated.
'use strict';
var FireMap = can.Map.extend({
'setup':function(snapshot){
this.new = true;
// Get the data from the snapshot.
var data = snapshot.val();
// Save the fb ref with it.
this.fb = {
// The ref to the data.
ref:snapshot.ref()
};
this._super(data);
},
'init':function(){
var self = this;
// When an attribute changes, update firebase.
this.bind('change', function(ev, attr, how, newVal, oldVal){
var data = this.attr();
delete data.fb;
this.fb.ref.set(data);
});
// Listen for updates from Firebase.
this.fb.ref.on('value', function(snapshot){
if (!self.new) {
var data = snapshot.val();
self.attr(data);
console.info('Applied update from Firebase');
} else {
self.new = false;
}
});
}
});
FireMap.List = can.List.extend({
Map:FireMap
}, {});
module.exports = FireMap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment