     @emitter.on 'did-update-style-element', callback
 
   attachedCallback: ->
+    @attached = true
+
     @subscriptions = new CompositeDisposable
     @subscriptions.add atom.styles.observeStyleElements(@styleElementAdded.bind(this))
     @subscriptions.add atom.styles.onDidRemoveStyleElement(@styleElementRemoved.bind(this))
     @subscriptions.add atom.styles.onDidUpdateStyleElement(@styleElementUpdated.bind(this))
+
+  detachedCallback: ->
+    @attached = false
+    @subscriptions.dispose()
 
   styleElementAdded: (styleElement) ->
     return unless styleElement.context is @context

{Emitter, CompositeDisposable} = require 'event-kit'

class StylesElement extends HTMLElement
  createdCallback: ->
    @emitter = new Emitter
    @styleElementClonesByOriginalElement = new WeakMap

    @emitter.emit 'did-update-style-element', styleElementClone

  contextChanged: ->
    @context = @getAttribute('context')
    if @attached
      @styleElementRemoved(child) for child in Array::slice.call(@children)
      @styleElementAdded(styleElement) for styleElement in atom.styles.getStyleElements()

module.exports = StylesElement = document.registerElement 'atom-styles', prototype: StylesElement.prototype
