Skip to content

Instantly share code, notes, and snippets.

@pcantrell
Created November 19, 2012 21:01
Show Gist options
  • Save pcantrell/4113853 to your computer and use it in GitHub Desktop.
Save pcantrell/4113853 to your computer and use it in GitHub Desktop.
Property observers in Javascript
// Model with property observers:
Model = function() {}
Model.prototype.observe = function(prop, observer) {
this._observers = this._observers || {}
if(!this._observers[prop]) {
this._observers[prop] = []
var privateProp = "_" + prop // foo is backed by _foo
this[privateProp] = this[prop] // copy current value of foo (if any) to _foo
Object.defineProperty(this, prop, {
get: function() {
return this[privateProp]
},
set: function(newVal) {
var oldVal = this[privateProp]
this[privateProp] = newVal
_.each(this._observers[prop],
function(observer) { observer(newVal, oldVal, prop) })
return newVal
}
})
}
var boundObserver = observer.bind(this)
this._observers[prop].push(boundObserver)
return boundObserver
}
Model.prototype.unobserve = function(prop, observer) {
if(this._observers[prop])
this._observers[prop] = _.without(this._observers[prop], observer)
}
// Try it out:
m0 = new Model()
m1 = new Model()
m0.foo = 3
var obs0 = m0.observe('foo', function() { console.log("m0 foo changed", this, arguments) })
var obs1 = m1.observe('foo', function() { console.log("m1 foo changed", this, arguments) })
console.log("m0.foo = ", m0.foo)
console.log("m1.foo = ", m1.foo)
m0.foo = 4
m1.foo = 40
console.log("m0.foo = ", m0.foo)
console.log("m1.foo = ", m1.foo)
m0.observe('foo', function() { console.log("m0 foo 2nd obs", this, arguments) })
m0.foo = 5
m1.foo = 50
m0['foo'] = 6
m1['foo'] = 60
console.log("m0.foo = ", m0.foo)
console.log("m1.foo = ", m1.foo)
m0.unobserve('foo', obs0)
m0.foo = 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment