Jakub Truneček
Jakub Truneček

Reputation: 8990

Binded variable is not synced in time

How is possible, that binding have latency?

App.SomeRoute = Ember.Route.extend
   actions:
      someAction: ->
          console.log @controllerFor('some').get('foo')
          Ember.run.later (=> console.log @controllerFor('some').get('foo')), 10

App.SomeController = Ember.ObjectController.extend()

App.OtherController = Ember.ObjectController.extend
    needs: ['some']
    fooBinding: 'controllers.some.foo'

    action:
        changeIt: ->
             @set('foo', 'bar')
             @send('someAction')

If action changeIt is evoked (from view for example) console output will be undefined, but after a little delay it will be bar.

What I am doing wrong?

Upvotes: 0

Views: 50

Answers (1)

Marcio Junior
Marcio Junior

Reputation: 19128

This is the expected behavior, when you change a bound property, the syncronization isn't performed immediatelly, it's just scheduled and called later.

This is important because if we have a fooBinding: 'controllers.some.foo'. Doesn't matter how many times the foo is changed, the controllers.some.foo property just need to be updated once with the final result. With this, we avoid to trigger uneeded observers, and save processing.

You can force the scheduled syncronization queue to flush using Ember.run.sync(), with the following code:

App.SomeRoute = Ember.Route.extend
   actions:
      someAction: ->
          Ember.run.sync()
          # now you can see the updated value
          console.log @controllerFor('some').get('foo')              

App.SomeController = Ember.ObjectController.extend()

App.OtherController = Ember.ObjectController.extend
    needs: ['some']
    fooBinding: 'controllers.some.foo'

    action:
        changeIt: ->
             @set('foo', 'bar')
             @send('someAction')

Keep in mind that this is just an example, for you see the updated value. The use of Ember.run.sync() isn't recommended.

Upvotes: 2

Related Questions