Adding observers after object initialization?


#1

I’d like to conditionally be able to add observers after object initialization, I tried something as follows but no dice:


App.SomeObj = Ember.Object.extend

  init: ->
    @_super()
    observer = Ember.observer ->
      console.log 'it changed!!'
    , 'someAttr'
    @set('ourCrazyObserver', observer)

o = App.SomeObj.create()
o.set('someAttr', 'derp')

#2

Figured it out, you can do the following

App.SomeObj = Ember.Object.extend

  init: ->
    @_super()
    
    # create method to fire on attr change
    observer = ->
      console.log 'it changed!!'

    # optional but helpful if we want to remove observer later
    # since removeObserver needs the same method
    @set('ourCrazyObserver', observer)

    # finally register observer
    @addObserver('someAttr', @, observer)