Created
January 13, 2014 23:09
-
-
Save jchris/8409900 to your computer and use it in GitHub Desktop.
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
// 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