Last active
December 31, 2015 20:59
-
-
Save mrgenixus/8044179 to your computer and use it in GitHub Desktop.
ObjectWatch "I like to watch"
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 watch = require('watch'); | |
| module.exports = function MyObject (){ | |
| } | |
| MyObject.prototype.printMe = function(){ | |
| console.log(JSON.stringify(this)); | |
| } | |
| watch(MyObject.prototype, function(name, args){ | |
| console.log('NAME', name /*, 'ARGS', args, this*/); | |
| }); | |
| // (new MyObject).printMe() // => usual output, prepended with a log of NAME: print_me |
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
| define(function(require, exports, module) { | |
| var _ = require('underscore'); | |
| var slice = function(subject, length){ | |
| Array.prototype.slice.call(subject, length); | |
| } | |
| module.exports = _.watch = function watch(p, callback, blacklist, whitelist) { | |
| console.log("I like to watch"); | |
| var include_methods = _.isArray(whitelist) ? whitelist : _.functions(p); | |
| var exclude_methods = _.isArray(blacklist) ? blacklist : []; | |
| var inspector = _.isFunction(callback) ? callback : function() {}; | |
| var orig = {}; | |
| var wrappable_methods = _.difference(include_methods, _.functions(_), blacklist); | |
| _.each(wrappable_methods, function(name){ | |
| orig[name] = p[name]; //save orig; | |
| var proxy = function(func){ | |
| var args = slice(arguments,1); | |
| var principalReturnValue = func.apply(this,args); | |
| inspect = _.partial(inspector, name, principalReturnValue); | |
| if (inspect.apply(this, args)) func.restore(); | |
| return principalReturnValue; | |
| }; | |
| p[name] = _.wrap(p[name], proxy); | |
| p[name].orig = orig[name]; //attach orig to returned function; | |
| p[name].restore = function(){ | |
| p[name] = p[name].orig; | |
| }; | |
| }); | |
| return orig; | |
| }; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment