Skip to content

Instantly share code, notes, and snippets.

@koolb
Forked from eligrey/object-watch.js
Last active August 29, 2015 14:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save koolb/fb9c8238372590814e34 to your computer and use it in GitHub Desktop.
/*
* 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

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