Skip to content

Instantly share code, notes, and snippets.

@jchris
Created January 13, 2014 23:09
Show Gist options
  • Save jchris/8409900 to your computer and use it in GitHub Desktop.
Save jchris/8409900 to your computer and use it in GitHub Desktop.
// object that emits changed events
// when watched fields are changed
var events = require('events'),
util = require("util");
//var myObj = new EventObject("fields", "to", "watch")
// doc = myObj.doc
// myObj.on("set", function(field){console.log("changed", field)})
// doc.watch = "foo"
// #> changed watch
var EventObject = module.exports = function() {
events.EventEmitter.call(this);
this.doc = makeObjectWatchingFields(this, Array.prototype.slice.apply(arguments))
};
util.inherits(EventObject, events.EventEmitter);
function makeObjectWatchingFields(ee, fields) {
var obj = {}, values = {};
fields.forEach(function(field){
Object.defineProperty(obj, field, {
get: function(){ return values[field]; },
set: function(value){
values[field] = value;
ee.emit("set", field)
}
});
})
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment