View#subscribe subscribes to an event emitter

This commit is contained in:
Corey Johnson & Nathan Sobo 2012-12-14 14:40:51 -08:00
parent 528fae9466
commit b822cd7779
2 changed files with 28 additions and 7 deletions

View File

@ -1,20 +1,25 @@
{View, $$} = require 'space-pen'
EventEmitter = require 'event-emitter'
describe "SpacePen extensions", ->
class TestView extends View
@content: -> @div()
[view, parent, observeHandler] = []
[view, parent] = []
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)", ->
observeHandler = null
beforeEach ->
observeHandler = jasmine.createSpy("observeHandler")
view.observeConfig "foo.bar", observeHandler
expect(view.hasParent()).toBeTruthy()
it "observes the keyPath and destroys the subscription when unsubscribe is called", ->
expect(observeHandler).toHaveBeenCalledWith(undefined)
observeHandler.reset()
@ -32,9 +37,21 @@ describe "SpacePen extensions", ->
expect(observeHandler).not.toHaveBeenCalled()
it "unsubscribes when the view is removed from the DOM", ->
it "unsubscribes when the view is removed", ->
observeHandler.reset()
parent.remove()
config.foo = { bar: "hello" }
config.update()
expect(observeHandler).not.toHaveBeenCalled()
describe "View#subscribe(eventEmitter, eventName, callback)", ->
[emitter, eventHandler] = []
beforeEach ->
eventHandler = jasmine.createSpy 'eventHandler'
emitter = $$ -> @div()
view.subscribe emitter, 'foo', eventHandler
it "subscribes to the given event emitter and unsubscribes when unsubscribe is called", ->
emitter.trigger "foo"
expect(eventHandler).toHaveBeenCalled()

View File

@ -6,9 +6,13 @@ originalRemove = View.prototype.remove
_.extend View.prototype,
observeConfig: (keyPath, callback) ->
@subscribe(config.observe(keyPath, callback))
@addSubscription(config.observe(keyPath, callback))
subscribe: (subscription) ->
subscribe: (eventEmitter, eventName, callback) ->
eventEmitter.on eventName, callback
@addSubscription(destroy: -> eventEmitter.off eventName, callback)
addSubscription: (subscription) ->
@subscriptions ?= []
@subscriptions.push(subscription)