Adam Knights
Adam Knights

Reputation: 2151

In an Ember route how can I check if an action exists?

In a component it is really easy to have an optional action provided to the component. In the JS of the component I can write:

if (this.get('someAction')) {
  this.sendAction('someAction');
}

In my application route I have a 'generic action' that saves me providing widget components with long lists of actions, it looks like this:

genericAction: function(customActionName, customActionParams) {
  this.send(customActionName, customActionParams);
}

For various reasons (including using genericAction in some components to fire an action a test could subscribe to, but the app not necessarily use in some hard to test async/pretender workflows) I would prefer to check the action exists, i.e:

genericAction: function(customActionName, customActionParams) {
  if (this.get(customActionName)) {
    this.send(customActionName, customActionParams);
  }
}

Similar to how you can in a component, however this does not work, nor does this.controller.get(customActionName).

Other than keeping a hard coded list of actions, how can I achieve this?

Upvotes: 2

Views: 1698

Answers (3)

Pedro Romão
Pedro Romão

Reputation: 2327

if you are in a component you can use

   if (this.get('yourActionName')) { }

Upvotes: 0

siva - abc
siva - abc

Reputation: 181

You can check for the actions in controller.actions. In your case, you have to check as

   if(Em.get(this.controller.actions, actionName)) {
         this.get('controller').send(actionName);
   }

Here is a demo

Upvotes: 2

Adam Knights
Adam Knights

Reputation: 2151

If you keep your actions in the routes/application.js file itself then the code would be

In Ember 2.0 or later:

   if(Em.get(this.actions, actionName)) {
         this.send(actionName);
   }

In Ember 1.13

this.actions is undefined in Ember 1.13, you have to use this._actions

   if(Em.get(this._actions, actionName)) {
         this.send(actionName);
   }

If you need to support both Ember 1.x and 2.x then use something like:

   let actions = this.actions || this._actions;
   if(Em.get(actions, actionName)) {
         this.send(actionName);
   }

If you keep your actions in the application controller (controllers/application.js) then siva - abc's answer works great.

Upvotes: 5

Related Questions