Add Config#observe, which watches a key path for changes

This commit is contained in:
Nathan Sobo 2012-12-12 18:05:28 -08:00 committed by Kevin Sawicki & Nathan Sobo
parent aedc86705e
commit 0a1b389994
2 changed files with 52 additions and 1 deletions

View File

@ -0,0 +1,34 @@
describe "Config", ->
describe "#observe(keyPath)", ->
observeHandler = null
beforeEach ->
observeHandler = jasmine.createSpy("observeHandler")
config.foo = { bar: { baz: "value 1" } }
config.observe "foo.bar.baz", observeHandler
it "fires the given callback with the current value at the keypath", ->
expect(observeHandler).toHaveBeenCalledWith("value 1")
it "fires the callback every time the observed value changes", ->
observeHandler.reset() # clear the initial call
config.foo.bar.baz = "value 2"
config.update()
expect(observeHandler).toHaveBeenCalledWith("value 2")
observeHandler.reset()
config.foo.bar.baz = "value 1"
config.update()
expect(observeHandler).toHaveBeenCalledWith("value 1")
it "fires the callback when the full key path goes into and out of existence", ->
observeHandler.reset() # clear the initial call
delete config.foo.bar
config.update()
expect(observeHandler).toHaveBeenCalledWith(undefined)
observeHandler.reset()
config.foo.bar = { baz: "i'm back" }
config.update()
expect(observeHandler).toHaveBeenCalledWith("i'm back")

View File

@ -6,7 +6,7 @@ module.exports =
class Config
configDirPath: fs.absolute("~/.atom")
configJsonPath: fs.absolute("~/.atom/config.json")
userInitScriptPath: fs.absolute("~/.atom/atom.coffe")
userInitScriptPath: fs.absolute("~/.atom/atom.coffee")
load: ->
if fs.exists(@configJsonPath)
@ -36,8 +36,25 @@ class Config
requireUserInitScript: ->
try
console.log @userInitScriptPath
require @userInitScriptPath if fs.exists(@userInitScriptPath)
catch error
console.error "Failed to load `#{@userInitScriptPath}`", error.stack, error
valueAtKeyPath: (keyPath) ->
value = this
for key in keyPath
break unless value = value[key]
value
observe: (keyPathString, callback) ->
keyPath = keyPathString.split('.')
value = @valueAtKeyPath(keyPath)
@on 'update', =>
newValue = @valueAtKeyPath(keyPath)
unless newValue == value
value = newValue
callback(value)
callback(value)
_.extend Config.prototype, EventEmitter