Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access actions from within an route in Ember.js

I'm updating the following route:

App.SomeRoute = Ember.Route.extend({
 events: {
   getMore: function(){
     var controller = this.get('controller'),
         nextPage   = controller.get('page') + 1,
         perPage    = controller.get('perPage'),
         items;

     items = this.events.fetchPage(nextPage, perPage);
     controller.gotMore(items, nextPage);
   },

   fetchPage: function(page, perPage){
     . . . .
   }
 }
});

For the most part, it works fine. However, the events syntax has been deprecated. Instead, we're suppose to use actions. Updating that works well enough, until I get to the line:

items = this.events.fetchPage(nextPage, perPage);

This throws the error:

TypeError: this.events is null

Unfortunately, I get the same error if I update the code to:

items = this.actions.fetchPage(nextPage, perPage);
=> TypeError: this.actions is null

How can I access action methods from within the same route?

like image 422
nullnullnull Avatar asked Sep 21 '13 04:09

nullnullnull


3 Answers

You have to use .send() to call a function inside the actions hash. Example:

    App.SomeRoute = Ember.Route.extend({
     actions: {
       getMore: function(){
         var controller = this.get('controller'),
             nextPage   = controller.get('page') + 1,
             perPage    = controller.get('perPage'),
             items;

        items = this.send('fetchPage', nextPage, perPage);
         controller.gotMore(items, nextPage);
      },

      fetchPage: function(page, perPage){
        .. . .
     }
   }
});
like image 142
phkavitha Avatar answered Nov 08 '22 15:11

phkavitha


It's also worth noting that you could potentially move fetchPage out of the actions hash. If it's only used 'internally' and does not respond directly to UI events, then it doesn't need to be in the actions hash. Then you can just call it with :

items = this.fetchPage(nextPage, perPage);
like image 32
Jeremy Green Avatar answered Nov 08 '22 16:11

Jeremy Green


You can use the send(actionName, args...) method to execute some action.

In your case:

this.send('fetchPage', nextPage, perPage);
like image 4
Marcio Junior Avatar answered Nov 08 '22 15:11

Marcio Junior