Add View#observeConfig as a space-pen extension

This commit is contained in:
Kevin Sawicki & Nathan Sobo 2012-12-14 11:08:18 -08:00 committed by Corey Johnson & Nathan Sobo
parent 97c6956e3f
commit b91c353d2b
5 changed files with 66 additions and 2 deletions

View File

@ -0,0 +1,41 @@
{View, $$} = require 'space-pen'
describe "SpacePen extensions", ->
class TestView extends View
@content: -> @div()
[view, parent, observeHandler] = []
beforeEach ->
view = new TestView
parent = $$ -> @div()
parent.append(view)
observeHandler = jasmine.createSpy("observeHandler")
view.observeConfig "foo.bar", observeHandler
expect(view.hasParent()).toBeTruthy()
describe "View#observeConfig(keyPath, callback)", ->
it "observes the keyPath and destroys the subscription when unsubscribe is called", ->
expect(observeHandler).toHaveBeenCalledWith(undefined)
observeHandler.reset()
config.foo = { bar: "hello" }
config.update()
expect(observeHandler).toHaveBeenCalledWith("hello")
observeHandler.reset()
view.unsubscribe()
config.foo.bar = "goodbye"
config.update()
expect(observeHandler).not.toHaveBeenCalled()
it "unsubscribes on remove", ->
observeHandler.reset()
view.remove()
expect(view.hasParent()).toBeFalsy()
config.foo = { bar: "hello" }
config.update()
expect(observeHandler).not.toHaveBeenCalled()

View File

@ -50,11 +50,14 @@ class Config
observe: (keyPathString, callback) ->
keyPath = keyPathString.split('.')
value = @valueAtKeyPath(keyPath)
@on 'update', =>
updateCallback = =>
newValue = @valueAtKeyPath(keyPath)
unless newValue == value
value = newValue
callback(value)
subscription = { destroy: => @off 'update', updateCallback }
@on 'update', updateCallback
callback(value)
subscription
_.extend Config.prototype, EventEmitter

View File

@ -13,6 +13,7 @@ RootView = require 'root-view'
Pasteboard = require 'pasteboard'
require 'jquery-extensions'
require 'underscore-extensions'
require 'space-pen-extensions'
windowAdditions =
rootViewParentSelector: 'body'

View File

@ -65,7 +65,7 @@ class TreeView extends ScrollView
@rootView.command 'tree-view:reveal-active-file', => @revealActiveFile()
@rootView.on 'active-editor-path-change', => @selectActiveFile()
@rootView.project.on 'path-change', => @updateRoot()
config.observe 'core.hideGitIgnoredFiles', => @updateRoot()
@observeConfig 'core.hideGitIgnoredFiles', => @updateRoot()
@selectEntry(@root) if @root

View File

@ -0,0 +1,19 @@
_ = require 'underscore'
{View} = require 'space-pen'
originalRemove = View.prototype.remove
_.extend View.prototype,
observeConfig: (keyPath, callback) ->
@subscribe(config.observe(keyPath, callback))
subscribe: (subscription) ->
@subscriptions ?= []
@subscriptions.push(subscription)
unsubscribe: ->
subscription.destroy() for subscription in @subscriptions ? []
remove: (args...) ->
@unsubscribe()
originalRemove.apply(this, args)