Adam Knights
Adam Knights

Reputation: 2151

Ember call an action on the application route from within the application routes setupController

I've setup a basic example to illustrate what I am trying to achieve. I am using setupController from within the application route, and have an action called addToSidebar. Within setupController I want to call the action but get the error:

Nothing handled the action 'addToSidebar'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.

Where else can I send the action from in my application route?

Code

routes/application.js

Ember.Route.extend({
  setupController: function(controller) {
  controller.set('numbers', [1, 2]);

  var someImportantVariable = true;

  if (someImportantVariable) {
    this.send('addToSidebar');
  }
  },
  actions: {
    addToSidebar: function() {
      var controller = this.controller;
      controller.get('numbers').addObject(controller.get('numbers.length') + 1);
    }
  }
});

application.hbs

 <div class="sidebar">
   Pets:
   {{#each numbers as |num|}}
     {{num}}
   {{/each}}
 </div>
 <div class="mainArea">
    {{outlet}}
 </div>

In my real life example the variable var controller = this.controller; will be decided by some more complex logic coming back from the forfilled models.

JS Bin I've setup a jsbin that shows the error I receive:

http://emberjs.jsbin.com/pedato/edit?html,css,js,output

Uncomment this.send('addToSidebar'); to see it.

Upvotes: 0

Views: 833

Answers (1)

Daniel
Daniel

Reputation: 18672

Just wrap sending action in Ember.run.next:

if (someImportantVariable) {
    Ember.run.next(this, function() {
        this.send('addToSidebar');
    });    
}

It makes sure that it action will be fired at later time, when all stuff is properly initialized.

Working demo.

Upvotes: 2

Related Questions