Migrate path watching to new subscription added/removed events

This commit is contained in:
Kevin Sawicki
2013-10-14 15:44:17 -07:00
parent 6030edcf0a
commit c797995597
2 changed files with 23 additions and 19 deletions

View File

@@ -20,6 +20,11 @@ class Directory
# + symlink:
# A {Boolean} indicating if the path is a symlink
constructor: (@path, @symlink=false) ->
@on 'first-contents-changed-subscription-will-be-added', =>
@subscribeToNativeChangeEvents()
@on 'last-contents-changed-subscription-removed', =>
@unsubscribeFromNativeChangeEvents()
# Public: Returns the basename of the directory.
getBaseName: ->
@@ -89,14 +94,6 @@ class Directory
directories.concat(files)
# Private:
afterSubscribe: ->
@subscribeToNativeChangeEvents() if @subscriptionCount() == 1
# Private:
afterUnsubscribe: ->
@unsubscribeFromNativeChangeEvents() if @subscriptionCount() == 0
# Private:
subscribeToNativeChangeEvents: ->
@watchSubscription = pathWatcher.watch @path, (eventType) =>

View File

@@ -25,6 +25,20 @@ class File
constructor: (@path, @symlink=false) ->
throw new Error("#{@path} is a directory") if fsUtils.isDirectorySync(@path)
@handleEventSubscriptions()
handleEventSubscriptions: ->
eventNames = ['contents-changed', 'moved', 'removed']
subscriptionsAdded = eventNames.map (eventName) -> "first-#{eventName}-subscription-will-be-added"
@on subscriptionsAdded.join(' '), =>
@subscribeToNativeChangeEvents()
subscriptionsRemoved = eventNames.map (eventName) -> "last-#{eventName}-subscription-removed"
@on subscriptionsRemoved.join(' '), =>
subscriptionsEmpty = _.every eventNames, (eventName) => @getSubscriptionCount(eventName) is 0
@unsubscribeFromNativeChangeEvents() if subscriptionsEmpty
# Private: Sets the path for the file.
setPath: (@path) ->
@@ -88,14 +102,6 @@ class File
exists: ->
fsUtils.exists(@getPath())
# Private:
afterSubscribe: ->
@subscribeToNativeChangeEvents() if @exists() and @subscriptionCount() == 1
# Private:
afterUnsubscribe: ->
@unsubscribeFromNativeChangeEvents() if @subscriptionCount() == 0
# Private:
handleNativeChangeEvent: (eventType, path) ->
if eventType is "delete"
@@ -125,11 +131,12 @@ class File
# Private:
subscribeToNativeChangeEvents: ->
@watchSubscription = pathWatcher.watch @path, (eventType, path) =>
@handleNativeChangeEvent(eventType, path)
unless @watchSubscription?
@watchSubscription = pathWatcher.watch @path, (eventType, path) =>
@handleNativeChangeEvent(eventType, path)
# Private:
unsubscribeFromNativeChangeEvents: ->
if @watchSubscription
if @watchSubscription?
@watchSubscription.close()
@watchSubscription = null