mirror of
https://github.com/pulsar-edit/pulsar.git
synced 2024-09-20 15:37:46 +03:00
Add Config#observe
, which watches a key path for changes
This commit is contained in:
parent
aedc86705e
commit
0a1b389994
34
spec/app/config-spec.coffee
Normal file
34
spec/app/config-spec.coffee
Normal 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")
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user