简体   繁体   中英

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?

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){
        .. . .
     }
   }
});

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);

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

In your case:

this.send('fetchPage', nextPage, perPage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM