Skip to content

Instantly share code, notes, and snippets.

@toropanov
Created May 12, 2015 16:02
Show Gist options
  • Save toropanov/250d3f361a54bb2c6d80 to your computer and use it in GitHub Desktop.
Save toropanov/250d3f361a54bb2c6d80 to your computer and use it in GitHub Desktop.
Observe objects for changes
class ObjectObserver extends Eventual
constructor: (@_object)->
super
@events_list = ['update']
Object.defineProperty this, 'value', {
get: -> @_object
set: (new_value)->
unless @object_compare(@_object, new_value)
old_value = $.extend({}, @_object)
@_object = $.extend(true, @_object, new_value)
@trigger 'update', old_value, @_object
return @_object
}
update: (new_value)->
return @value unless Object.isObject(new_value)
@value = new_value
object_compare: (obj1, obj2)->
JSON.stringify(obj1) == JSON.stringify(obj2)
obj = {
price: {}
beach_distance: {}
}
@object_observer = new ObjectObserver(obj)
@object_observer.on 'update', (old_object, new_object)->
console.log '%O => %O', old_object, new_object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment