Maksim Luzik
Maksim Luzik

Reputation: 6713

Calling controller method from controller action in Ember 2.0

Ember 2.0 is really giving me a hard time to understand the new functionality. I want to call a method in the controller from the action function, but dont seem to find a way how. Wasted some time on this already

I have read this: calling method from action of controller in emberjs but it is only working for Ember 1.x as in Ember 2.0 there is no ArrayController anymore and I cannot use this.send().

Basically what I would need is:

App.SomeController = Ember.Controller.extend({
   methodFunction: function(data) {
      console.log("YEY", data);
   }
   actions: {
      sessionAction: function(data) {
          this.methodFunction(data);
      }
   }
});

Problem is that this.methodFunction is not available

Upvotes: 1

Views: 781

Answers (1)

Daniel
Daniel

Reputation: 18672

Code you've provided in question has an error:

SyntaxError: controllerName.js: unknown: Unexpected token (7:3)(…)

You're missing , after methodFunction declaration. Fix:

App.SomeController = Ember.Controller.extend({
   methodFunction: function(data) {
      console.log("YEY", data);
   },
   actions: {
      sessionAction: function(data) {
          this.methodFunction(data);
      }
   }
});

For template:

<button {{action 'sessionAction' 'Example data'}}>Send session action</button>

It logs correctly:

YEY Example data

By the way, you can also take advantage of ES2015 syntax:

export default Ember.Controller.extend({
   methodFunction(data) {
      console.log("YEY", data);
   },
   actions: {
      sessionAction(data) {
          this.methodFunction(data);
      }
   }
});

Upvotes: 2

Related Questions