Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* object.watch polyfill
*
* 2014-08-23
*
* By koolb@hotmail.com
*
* 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
@koolb
Copy link
Author

koolb commented Aug 24, 2014

object-watch in coffee

@CullenShane
Copy link

CullenShane commented Apr 9, 2015

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