-
-
Save koolb/fb9c8238372590814e34 to your computer and use it in GitHub Desktop.
This file contains 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.watch polyfill | |
* | |
* 2014-08-23 | |
* | |
* By [email protected] | |
* | |
* Usage: | |
* obj.watch('a', (name, old, new) -> console.log "#{name} changed from #{old} to #{new}" | |
* | |
* Public Domain. | |
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. | |
*/ | |
# object.watch | |
unless Object::watch? | |
Object.defineProperty Object::, "watch", | |
enumerable: false, configurable: true, writeable: false, value: (prop, handler) -> | |
oldval = @[prop] | |
newval = oldval | |
getter = () -> newval | |
setter = (val) -> oldval = newval; newval = handler.call(@, prop, oldval, val) | |
Object.defineProperty @, prop, get: getter, set: setter, enumerable: true, configurable: true if delete @[prop] | |
unless Object::unwatch? | |
Object.defineProperty Object::, "unwatch", | |
enumerable: false, configurable: true, writeable: false, value: (prop) -> | |
prop = @[prop] | |
delete @[prop] | |
@[prop] = val |
In unwatch:
prop = @[prop] should be
val = @[prop]
because val is not been set otherwise.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
object-watch in coffee