diff --git a/src/directory.coffee b/src/directory.coffee index 0a06e7f8b..b242386ef 100644 --- a/src/directory.coffee +++ b/src/directory.coffee @@ -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) => diff --git a/src/file.coffee b/src/file.coffee index 3bb1b39f7..88a91650b 100644 --- a/src/file.coffee +++ b/src/file.coffee @@ -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