Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Set emits events

  • Loading branch information...
commit e9fee1bed111cedd32e27af58eee80f73a778010 1 parent 112c05c
@markevans authored
Showing with 47 additions and 1 deletion.
  1. +8 −1 src/set.coffee
  2. +39 −0 test/src/set.coffee
View
9 src/set.coffee
@@ -1,4 +1,4 @@
-class egg.Set
+class egg.Set extends egg.Base
constructor: (opts={})->
@items = {}
@@ -11,12 +11,19 @@ class egg.Set
unless @items[id]
@items[id] = item
delete @array
+ @emit 'add', instance: item if @hasSubscribers
+ true
remove: (item)->
id = item.eggID()
if @items[id]
delete @items[id]
delete @array
+ @emit 'remove', instance: item if @hasSubscribers
+ true
+
+ notifyChanged: (instance, from, to)->
+ @emit 'change', instance: instance, from: from, to: to if @hasSubscribers
count: (filter)->
return @toArray().length unless filter
View
39 test/src/set.coffee
@@ -120,3 +120,42 @@ describe 'egg.Set', ->
set.remove b1
expect( set.toArray() ).toEqual([b2])
expect( set.count() ).toEqual(1)
+
+ describe 'events', ->
+ bean = null
+
+ beforeEach ->
+ bean = Bean.create()
+
+ it "should not emit anything if no-one's listening", ->
+ set = new egg.Set
+ spyOn(set, 'emit')
+ set.add bean
+ expect( set.emit ).not.toHaveBeenCalled()
+
+ it "should emit add if someone's listening", ->
+ set = new egg.Set
+ spyOn(set, 'emit')
+ set.on 'blah', ->
+ set.add bean
+ expect( set.emit ).toHaveBeenCalledWith('add', instance: bean)
+
+ it "should not emit add if already there", ->
+ set = new egg.Set items: [bean]
+ spyOn(set, 'emit')
+ set.on 'blah', ->
+ set.add bean
+ expect( set.emit ).not.toHaveBeenCalled()
+
+ it "should emit change when notified", ->
+ set = new egg.Set items: [bean]
+ spyOn(set, 'emit')
+ set.on 'blah', ->
+ set.notifyChanged bean, {gar: 'blud'}, {gar: 'booney'}
+ expect( set.emit ).toHaveBeenCalledWith('change', instance: bean, from: {gar: 'blud'}, to: {gar: 'booney'})
+
+ it "should not emit change when notified if nothing is listening", ->
+ set = new egg.Set items: [bean]
+ spyOn(set, 'emit')
+ set.notifyChanged bean, {gar: 'blud'}, {gar: 'booney'}
+ expect( set.emit ).not.toHaveBeenCalled()
Please sign in to comment.
Something went wrong with that request. Please try again.