Ember: Get route instance from the controller - ember.js

I have a multi-step flow that the user can go through sequentially or jump straight to a section (if the sections in between are completed). I think this logic should be in the Route object. However, from within the controller, how do I access the route instance. For example, it would be ideal to be able to do something like this in the controller:
App.Flow = Em.ObjectController.extend({
submit: function(){
// Validation and XHR requests
// ...
// Go to the next step
route.goToNextStep();
}
}

From within a controller, you can access the router via this.get('target'). So this.get('target').send('goToNextStep') should work.
Like so:
App.Flow = Em.ObjectController.extend({
submit: function(){
// ...
this.get('target').send('gotoNextStep');
}
}
App.FlowRoute = Ember.Route.extend({
events: {
gotoNextStep: function(){
// ...
this.transitionTo(routeName);
}
}
}

You need to get the route for such conditions,
so from the controller just say,
App.Flow = Em.ObjectController.extend({
submit: function(){
var self =this;
// Validation and XHR requests
// ...
// Go to the next step
self.send('goToNextStep');
}
}
and define your goToNextStep event in your route's event hash

'this' is what points to the router, but you shouldn't add any methods to that prototype. Instead, make some sort of event that triggers the transition to the next step.

In addition to target, another way to do this in Ember now is with getOwner.
For example, to send an action to your application route:
import Component from '#ember/component';
import { action } from '#ember/object'; // https://github.com/pzuraq/ember-decorators-polyfill
import { getOwner } from '#ember/application';
export default class MyTopLevelComponent extends Component {
#action
closeModal() {
getOwner(this).lookup('route:application').send('closeModal');
}
});

Related

How to get next route after the current route deactivate.?

I have some code that uses route 'deactivate' method as follows.
deactivate: function() {
this._super();
//some code here
}
Is there a way to identify where is user trying to go(route of URL) after this route deactivates?
I would encourage you to use willTransition actions method hook for this purpose since that will be called before deactivate hook method.
transition.targetName will provide the target route.
actions: {
willTransition(transition) {
this._super(...arguments);
console.log('willTransition user ', transition.targetName);
}
}

Ember deprecation: replacing a view with a component

Hey I'm facing a problem with removing a view.
The view is used as navbar
{{view "inner-form-navbar" navbarParams=innerNavObject}}
Where params look like this
innerNavObject: {
...
routeToReturn: 'someroute.index',
...
},
On the navbar there's a small "back" button when it's clicked the parent index route is opened.
It currently works like this:
this.get('controller').transitionToRoute(routeToReturn);
But this won't work in a component and is sketchy anyways. Do i need to somehow inject router to component? Or has anyone gotten a solution for this? The navbar is used in so many places so adding a property to navbarObject to have certain action defined is not a really good solution imo.
Went for this solution :
export default {
name: 'inject-store-into-components',
after: 'store',
initialize: function(container, application) {
application.inject('component', 'store', 'service:store');
application.inject('component', 'router', 'router:main');
}
};
Now i can do
this.get('router').transitionTo('blah')
Well you can try to use a service that provides the routing capabilities and then inject into the component.
There's an addon that seems to do just that - ember-cli-routing-service
Example taken from the link, adapted for you scenario:
export default Ember.Component.extend({
routing: Ember.inject.service(),
someFunc () {
this.get('routing').transitionTo(this.get('innerNavObject'). routeToReturn);
}
});
Having a component control your route/controller is typically bad practice. Instead, you would want to have an action that lives on your route or controller. Your component can then send that action up and your route or controller will catch it (data down, actions up).
In your controller or route, you would have your transition action:
actions: {
transitionFunction(route) {
this.transitionTo(route);
}
}
You would also define the the current route name in your route or controller and pass that to your nav bar component. Controller could then look like:
export default Controller.extend({
application: inject.controller(),
currentRoute: computed('application.currentRouteName', function(){
return get(this, 'application.currentRouteName');
}),
actions: {
transitionFunction(route) {
this.transitionTo(route);
}
}
});
Then call your component and pass the currentRoute CP to it:
{{nav-bar-component currentRoute=currentRoute action='transitionFunction'}}
Then, in your component, you can have a function that finds the parent route from the currentRoute:
export default Component.extend({
click() { // or however you are handling this action
// current route gives us a string that we split by the . and append index
const indexRoute = get(this, currentRoute).split('.')[0] + '.index';
this.sendAction('action', indexRoute);
}
});
Extending a route
Per your comment, you may want to have this across multiple routes or controllers. In that case, create one route and have your others extend from it. Create your route (just as I created the Controller above) with the action. Then import it for routes you need:
import OurCustomRoute from '../routes/yourRouteName';
export default OurCustomRoute.extend({
... // additional code here
});
Then your routes will have access to any actions or properties set on your first route.

How do I reload data and update a bound element after a user clicks a button?

Why is it that when I click 'Random', the information in the template isn't reset and the data isn't update?
I have data that I want to display after a REST endpoint is successfully reached. The REST data that's returned is a random database record, so I don't need to worry about randomizing my request or anything. I only need to reach the server via that URL. In this case, the URL is: localhost:8000/api/verses/0
My handlebars template looks like this:
app/templates/verses.hbs
<div id="panel">
<h3>{{model.reference_number}}
<h3>{{model.body}}</h3>
<button {{action "getAnotherVerse"}}>Random</button>
</div>
{{outlet}}
So, when the 'Random' button is clicked, the following should be invoked:
app/controllers/verses.js
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.ObjectController.extend({
actions: {
getAnotherVerse: function() {
this.get('model').reload();
// This is where the text should be reset to the new data.
}
}
});
app/routers/verses.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('verse', '0');
}
});
When you fire getAnotherVerse you just take the current record(model) and simply reload it to fetch its latest data. I guess you want to call model method of your route once again, so model will be reset and you'll get brand new record from your server.
Move getAnotherVerse to your VersesRoute where you specify model for VersesController and try following code:
# app/routes/verses.js
model: function() {
return this.store.find('verse', '0');
},
actions: {
getAnotherVerse: function() {
this.refresh(); # beforeModel, model, afterModel, setupController will re-fire
}
}
If this still doesn't work, please try this:
# app/routes/verses.js
model: function() {
return this.store.fetch('verse', '0');
},
actions: {
getAnotherVerse: function() {
this.store.unloadAll('verse'); # I assume `verse` is your Model name
this.refresh(); # beforeModel, model, afterModel, setupController will re-fire
}
}
Your telling Ember Data to find the record with id = 0. Just guessing that your API endpoint is treating 0 as a special case and returning a record that does have an actual id.
Because Ember Data is using an identity map under the hood I'm guessing that when you call reload the data is creating a new record in the store. And therefore isn't triggering updates on the record that is being used for the model.
A better approach would be to just use
var that = this;
Ember.$.get('localhost:8000/api/verses/0')
.then(function(data) {
that.set('model', data);
});
You could push the data into the store too http://emberjs.com/guides/models/pushing-records-into-the-store/ and then it would be available if you need to find it by id later.
Another approach would be to create a custom adapter / serializer that could hide some of this, really depends on how your using ember data outside of this use case.

Emberjs call a method from an other object

This might be a silly question, but I can't find out anything about it anywhere...
I create a method in one of my controller to verify if the user session is still good, and I'm using this method in almost every page of my app in my beforeModel. But the thing is that I don't want to copy/paste the code every time in every route, this will be dirty and I really don't like it.
Lets say I have this controller :
App.LoginController = Ember.ObjectController.extend({
...
isSession: function() {
var session = this;
Ember.$
.get(host + '/session', function(data) {
console.log('DEBUG: Session OK');
})
.fail(function() {
console.log('DEBUG: Session FAIL');
session.transitionToRoute('login');
});
}
});
How can I call it in this router :
App.HomeRoute = Ember.Route.extend({
beforeModel: function(transition) {
//Here
},
model: function() {
return this.store.all('login');
}
});
I've tried this this.get('loginController').isSession(); but I receive this error Error while loading route: TypeError: Cannot call method 'isSession' of undefined
Thanks for the help !
[edit]
I don't have much to show but this :
My map
App.Router.map(function() {
this.route('login', { path: '/' });
this.route('home');
this.resource('enquiries', function() {
this.route('enquiry', { path: '/:enquiry_id' }, function() {
this.route('update');
});
});
});
Most likely I only Have a LoginController and my HomeRoute. (its the beginning of the app)
I don't need to create a Route for my Login because I have an action helper in my login template and I'm redirected to my Home template after that.
You need to use controllerFor() method in order to call method on controller from router. If method is an action you need to use send() method, like this.controllerFor('login').send('isSession')
App.HomeRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
transition.abort();
this.controllerFor('login').isSession()
}
});
If you don't need a return value from isSession you might consider making it an action on a top-level route. The router.send method in the docs has a pretty good example of how you declare actions as well as how you call them. Note that send is also a method you can call on a controller. Actions bubble up from a controller, to the parent route, and then all the way up the route hierarchy, as shown here

How to manually invoke a route in ember.js RC1

I have the following controller and I'd like to bubble up an event using send
App.PersonController = Ember.ObjectController.extend({
page: function(page) {
var model = PersonApp.Page.create({id: page});
this.send("person.page", model); //should bubble up ...
}
});
here is my route setup
PersonApp.Router.map(function(match) {
this.resource("person", { path: "/" }, function() {
this.route("page", { path: "/page/:page_id" });
});
});
here is the simple page model (shim basically)
PersonApp.Page = Ember.Object.extend({
});
although I'm using the route "person.page" and I'm passing a valid model I get the following error (seemingly the router does not have this route?)
Uncaught Error: Nothing handled the event 'person.page'.
If it helps debug the controller / router relationship I noticed inside my controller if I dump this.get('target') ...
_debugContainerKey: "router:main"
and if I dig further ... and print this
this.get('target').get('router')
I see a router w/ my route under the currentHandlerInfos array ... not sure if I should be this deep though
... another slight update
If I do this (full blown) it seems to modify the window.location but my model/setupController hooks on the route are never hit
this.get('target').get('router').transitionTo(route, model);
I think, send is just used for events of a route. Assuming your controller would call send like this:
//in the controller
this.send("personPage", model);
// a matching Route
App.PersonRoute = Ember.Route.extend({
events : {
personPage : function(page){
// this should be called
}
}
});
For your case you need to leverage transitionTo (your access on the router property was too much, i think. The router instance of Ember.Router has again a router property. Pretty confusing :-)).
this.get("target").transitionTo("person.page", model);