简体   繁体   中英

Ember js - how to trigger a controller action when route is activated

I need to trigger a controller action each time a controller is transitioned to (the 'modeller' route), but I can't seem to get it working. My router.js file is:

var Router = Ember.Router.extend({
  location: config.locationType,
  actions: {
    loading: function() {
        this.controllerFor('modeller').send('loading');
    },
    didTransition: function() {
        this.controllerFor('modeller').send('didTransition');
    }
  }
});

Router.map(function() {
  this.route('modeller', { path: 'modeller'});
  this.route('welcome', { path: '/'});
});
export default Router;

And my modeller controller:

export default Ember.Controller.extend({
  needs: 'modeller',

  loading: function () {
    console.log("loading")
  },

  didTransition: function () {
    console.log("didTransition")
  },
});

But I can't get any of those actions to log to the console. Any pointers greatly appreciated.

UPDATE:

Probably should have mentioned I'm using Ember 2.1.0!

So the solution I used was setupController - but I also needed to put that into a specific modeller route file under app/routes/modeller.js. Previously I was trying to do everything in the app/router.js and it didn't work there. So the final solution is:

# app/routes/modeller.js
import Ember from 'ember';
export default Ember.Route.extend({

  setupController: function(controller, model) {
    this.controllerFor('modeller').activate();
  }
});

and ..

 # app/controllers/modeller.js
 export default Ember.Controller.extend({
   needs: 'modeller',

   activate: function () {
     console.log("activate")
   },
 });

didTransition is a method on Route rather than on Controller which is why that method isn't getting called.

If you need to effect the controller from the route, the hook you would want would be setupController .

Best practice is to use components which would enable you to use the component lifecycle hooks .

Try to use willTransition in Route.

When a transition is attempted, whether via {{link-to}}, transitionTo, or a URL change, a willTransition action is fired on the currently active routes. This gives each active route, starting with the leaf-most route, the opportunity to decide whether or not the transition should occur.

https://guides.emberjs.com/v2.4.0/routing/preventing-and-retrying-transitions/

model hooks

activate & deactivate hooks of Ember.Route will also be called for every transition between routes, either of these two also you can use and inside you can call controller action method.

deactivate: function() {
    this._super();
     this.get('controller').send('actionName');
}

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