diff --git a/spec/app/config-spec.coffee b/spec/app/config-spec.coffee new file mode 100644 index 000000000..671d59db0 --- /dev/null +++ b/spec/app/config-spec.coffee @@ -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") diff --git a/src/app/config.coffee b/src/app/config.coffee index 619221d1d..610f3e216 100644 --- a/src/app/config.coffee +++ b/src/app/config.coffee @@ -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