Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger an action programmatically?

I have this view

  App.ApplicationView = Em.View.extend({
    templateName: 'application',

    actions: {
      myAction: function() {
        //
      }
    }
  });

Suppose I want to trigger manually that action from another view method, such as didInsertElement, like:

  App.ApplicationView = Em.View.extend({
    templateName: 'application',

    actions: {

      sidebarShowHome: function() {
        this.set('sidebarIsHome', true);
        this.set('sidebarIsNotifications', false);
        this.set('sidebarIsArchive', false);
      },
    },

    didInsertElement: function() {
      this.actions.sidebarShowHome();
    }
  });

How could I do it? this.actions is undefined from within a view method.

like image 917
Flavio Copes Avatar asked Sep 17 '13 12:09

Flavio Copes


3 Answers

You can use the TargetActionSupport mixin along with this.triggerAction:

App.ApplicationView = Ember.View.extend(Ember.TargetActionSupport, {
  templateName: 'application',
  actions: {
    myAction: function() {
      console.log('myAction');
    }
  },
  didInsertElement: function() {
    this.triggerAction({
      action:'myAction',
      target: this
    });
  }
});

By default using this.triggerAction() without parameters will send the action to the controller, however if you need to target a different destination define the target option as shown in the example.

Working demo.

Hope it helps.

like image 121
intuitivepixel Avatar answered Nov 02 '22 06:11

intuitivepixel


To call an action in the same controller you can use send.

this.send('nameOfAction', someParams);

To call an action in the parent controller from a component use sendAction.

this.sendAction('nameOfAction', someParams);
like image 15
Nelu Avatar answered Nov 02 '22 06:11

Nelu


The triggerAction() method only exists, if the view uses the Ember.TargetActionSupport mixin. If this is not the case, use this.get('controller').send('action'); instead.

like image 12
vanthome Avatar answered Nov 02 '22 06:11

vanthome