Ember Router transitionTo nested route with params - ember.js

App.Router.map(function() {
this.resource('documents', { path: '/documents' }, function() {
this.route('edit', { path: ':document_id/edit' });
});
this.resource('documentsFiltered', { path: '/documents/:type_id' }, function() {
this.route('edit', { path: ':document_id/edit' });
this.route('new');
});
});
And this controller with a subview event that basically transitions to a filtered document
App.DocumentsController = Ember.ArrayController.extend({
subview: function(context) {
Ember.run.next(this, function() {
//window.location.hash = '#/documents/'+context.id;
return this.transitionTo('documentsFiltered', context);
});
},
});
My problem is that this code works fine when Hash of page is changed.
But when I run the above code NOT w/ the location.hash bit and w/ the Ember native transitionTo I get a cryptic
Uncaught TypeError: Object [object Object] has no method 'slice'
Any clues?
Thanks
UPDATE:
App.DocumentsFilteredRoute = Ember.Route.extend({
model: function(params) {
return App.Document.find({type_id: params.type_id});
},
});
{{#collection contentBinding="documents" tagName="ul" class="content-nav"}}
<li {{action subview this}}>{{this.nameOfType}}</li>
{{/collection}}

The problem is that your model hook is returning an array, while in your transitionTo you are using a single object. As a rule of thumb your calls to transitionTo should pass the same data structure that is returned by your model hook. Following this rule of thumb i would recommend to do the following:
App.DocumentsController = Ember.ArrayController.extend({
subview: function(document) {
var documents = App.Document.find({type_id: document.get("typeId")});
Ember.run.next(this, function() {
return this.transitionTo('documentsFiltered', documents);
});
}
});
Note: I assume that the type_id is stored in the attribute typeId. Maybe you need to adapt it according to your needs.

Related

Ember.js: Uncaught TypeError: Cannot read property 'enter' of undefined on transitionTo

I have a fairly simple Ember.js app. Inside a view I call this.transitionTo which gives me the error:
Uncaught TypeError: Cannot read property 'enter' of undefined
The error is in ember.js at line 24596, where currentState is undefined
Here are the relevant parts of my app:
window.Plan = Ember.Application.create({});
Plan.Router = Ember.Router.extend({
location: 'hash'
});
Plan.IndexController = Ember.ObjectController.extend({
});
Plan.Router.map(function() {
this.route('application', { path: '/' })
this.route('index', { path: "/:current_savings/:monthly_deposit/:time_horizon" });
});
Plan.ApplicationRoute = Ember.Route.extend({
redirect: function(){
this.transitionTo('index', 200, 200, 200);
}
})
Plan.IndexRoute = Ember.Route.extend({
model: function(params) {
var result = this.store.find('calculation', params).then(function(data) {
return data.content[0];
});
return result;
}
});
Plan.CurrentSavingsTextField = Ember.TextField.extend({
focusOut: function() {
this.transitionTo('index', 150, 200, 200);
}
});
Plan.MonthlyContributionTextField = Ember.TextField.extend({
focusOut: function() {
this.transitionTo('index', 150, 200, 200);
}
});
Plan.TimeHorizonTextField = Ember.TextField.extend({
focusOut: function() {
this.transitionTo('index', 150, 200, 200);
}
});
Plan.Calculation = DS.Model.extend({
target_goal: DS.attr('number'),
target_return: DS.attr('number'),
expected_return: DS.attr('number'),
downside_probability: DS.attr('number')
});
Plan.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'plan/' + window.targetReturnId
});
HTML:
<script type="text/x-handlebars" data-template-name="index">
<div>
<div>Starting Balance: {{view Plan.CurrentSavingsTextField size="10"}}</div>
<div>Monthly Contribution: {{view Plan.MonthlyContributionTextField size="10"}}</div>
<div>Time Horizon: {{view Plan.TimeHorizonTextField size="10"}}</div>
</div>
<div>
<span>Plan Goal: {{target_goal}}</span>
<span>Required Return: {{target_return}}</span>
<span>Exp Return: {{expected_return}}</span>
<span>Downside Probability: {{downside_probability}}</span>
<span>Time Horizon: {{time_horizon}}</span>
</div>
</script>
This response is:
{
"calculations":[
{
"id":10,
"target_goal":3107800.0,
"target_return":0.089,
"expected_return":0.0708,
"downside_probability":0.0489
}
]
}
The app works as expected until I focus out of the text field, then I get the error.
Ember : 1.5.1
Ember Data : 1.0.0-beta.8.2a68c63a
Handlebars : 1.2.1
jQuery : 1.11.1
Past kingpin2k was totally wrong, I missed the statement about the transition from the view. I apologize.
transitionTo from a component isn't supported (at least from any documentation I could find)
You'll want to send an action out of the component and capture it in your controller or route.
Plan.CurrentSavingsTextField = Ember.TextField.extend({
focusOut: function() {
this.sendAction('go', 199, 200, 201);
}
});
Plan.IndexRoute = Ember.Route.extend({
model: function(params) {
var result = this.store.find('calculation', params);
//if you just wanted the first object
// result.then(function(collection){
// return collection.get('firstObject');
// });
return result;
},
actions:{
go: function(a, b, c){
console.log('transition');
this.transitionTo('index',a,b,c);
}
}
});
http://emberjs.jsbin.com/OxIDiVU/749/edit
This question is quite old but it still seems unanswered as far as my googling has gone. After playing around (Ember 0.13.0) I was able to get the following code to work from inside a component:
this.get('_controller').transitionToRoute('index', 150, 200, 200);
The _ infront of controller does feel like a bit of a hack and that it shouldn't really be accessible to userland code. get('controller') does infact return something completely different.
I do agree navigating from a view (Component) isn't best practice, but for my use case I have a few components that drop in to a dashboard for graphing etc which this is perfect for rather than calling out to controller actions. It helps me keep everything isolated inside a single component.

How to define a nested route to render when hitting the parent in Ember

I have a blog route, and a blog-post route.
Router:
App.Router.map(function () {
this.resource('blog', function () {
this.route('post', {path: ':id/:title'});
});
});
Routes:
App.BlogRoute = Ember.Route.extend({
model: function () {
return this.store.find('BlogPost');
}
});
App.BlogPostRoute = Ember.Route.extend({
model: function (params) {
return this.store.findById('BlogPost', params.id);
},
serialize: function (model, params) {
return {
id: model.get('id'),
title: Ember.String.dasherize(model.get('title'))
}
}
});
In my Handlebars template for the parent blog route I have an {{outlet}} that works fine when I click one of the {{#link-to}}s.
What I want to do is render by default the most recent (highest ID) blog post when a user goes to the /blog route.
I found this question and tried this as a result, to no avail:
App.BlogIndexRoute = Ember.Route.extend({
redirect: function () {
var latest = 3;
this.transitionTo('blog.post', {id: latest});
}
});
(latest is just a placeholder for this.model.pop() or whatever it needs to be.)
I just can't figure out how exactly to load the sub route with the data from the model.
You can fetch the model for any resource/route that has already been fetched (aka parent resources) using modelFor
App.BlogIndexRoute = Ember.Route.extend({
redirect: function () {
var blogs = this.modelFor('blog');
if(blogs.get('length')){
this.transitionTo('blog.post', blogs.get('firstObject')); // or blogs.findBy('id', 123)
}
}
});

emberjs: transitionToRoute Error no method 'addArrayObserver

From the 'job' route I am trying to transition to 'careers' route using following code.
<script type="text/x-handlebars" data-template-name="job">
<button {{action 'backToCareers' this}}>Back</button>
</script>
The controller with following gives 'Uncaught TypeError: Object # has no method 'addArrayObserver' ' error.
CareerApp.JobController = Ember.ObjectController.extend({
backToCareers: function(){
this.transitionToRoute('careers');
}
});
If I change the code(see below) to provide model object the error changes to 'Uncaught More context objects were passed than there are dynamic segments for the route: careers '
CareerApp.JobController = Ember.ObjectController.extend({
backToCareers: function(){
var jobs = CareerApp.Job.findAll();
this.transitionToRoute('careers', jobs);
}
});
Following is the code of my Model and the router
CareerApp.Job = Ember.Model.extend({
refNo: '',
title: ''
});
CareerApp.Job.reopenClass({
findAll: function(){
return $.getJSON("http://site/jobs").then(
function(response){
var jobs = Ember.A();
response.forEach(function(child){
jobs.pushObject(CareerApp.Job.create(child));
});
return jobs;
}
);
}
});
Router code
CareerApp.Router.map(function(){
this.resource('careers', {path: '/'});
this.resource('job', {path: '/jobs/:job_id'});
});
CareerApp.CareersRoute = Ember.Route.extend({
model:function(){
return CareerApp.Job.findAll();
}
});
CareerApp.CareersController = Ember.ArrayController.extend({
gradJobCount: function () {
return this.filterProperty('isExp', false).get('length');
}.property('#each.isExp')
});
The model hook is expected to return an array but you return a jQuery promise object. findAll should return an empty array which is filled when the callback is executed.
findAll: function() {
var jobs = [];
$.getJSON("http://site/jobs").then(function(response){
response.forEach(function(child){
jobs.pushObject(CareerApp.Job.create(child));
});
});
return jobs;
}
As you pass jobs to CarreersController, this one needs to be an ArrayController, maybe you have to define it manually

How to access a parent model within a nested index route using ember.js?

I have the following route structure
App.Router.map(function(match) {
this.route("days", { path: "/" });
this.resource("day", { path: "/:day_id" }, function() {
this.resource("appointment", { path: "/appointment" }, function() {
this.route("edit", { path: "/edit" });
});
});
});
When I'm inside the AppointmentIndexRoute I'm looking for a way to create a new model using some meta day from the day (parent) model but because the day model does not yet know about this appointment I'm unsure how to associate them until the appointment is created / and the commit is fired off.
Any help would be much appreciated
From within the AppointmentIndexRoute's model hook you can use modelFor('day') to access the parent model. For example:
App.AppointmentIndexRoute = Ember.Route.extend({
model: function(params) {
day = this.modelFor("day");
...
}
});
Another example is here: emberjs 1.0.0pre4 how do you pass a context object to a resource "...Index" route?
What if I am not using ember data? How do I get the parent id in a route like
this.resource('workspace',function () {
this.resource('workflow', {path: '/:workspace_id/workflow'}, function () {
this.route('show', {path: '/:workflow_id'});
});
});
This code will not work:
App.WorkflowShowRoute = Em.Route.extend({
model: function(params) {
var ws = this.modelFor('workspace'); //ws is undefined
return this.store.find('workflow', params.id, ws.id);
}
});
EDIT:
I found a workaround, it's not ideal but works exactly the way I want it.
this.resource('workspace',function () {
this.route('new');
this.route('show', {path: '/:workspace_id'});
//workflow routes
this.resource('workflow', {path: '/'}, function () {
this.route('new', {path:'/:workspace_id/workflow/new'});
this.route('show', {path: '/:workspace_id/workflow/:workflow_id'});
});
});
And in my workflow route, I can access the workspace_id jus as I expect from the params property:
App.WorkflowShowRoute = Em.Route.extend({
model: function(params) {
return this.store.find('workflow', params.workflow_id, params.workspace_id);
}
});
Finally, here is my link-to inside the workspace.show route helper:
{{#each workflow in workflows}}
<li>
{{#link-to 'workflow.show' this.id workflow.id}}{{workflow.name}}{{/link-to}}
</li>
{{/each}}

Same Ember.JS template for display/edit and creation

I am writing a CRUD application using Ember.JS:
A list of “actions” is displayed;
The user can click on one action to display it, or click on a button to create a new action.
I would like to use the same template for displaying/editing an existing model object and creating a new one.
Here is the router code I use.
App = Ember.Application.create();
App.Router.map(function() {
this.resource('actions', {path: "/actions"}, function() {
this.resource('action', {path: '/:action_id'});
this.route('new', {path: "/new"});
});
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('actions');
}
});
App.ActionsIndexRoute = Ember.Route.extend({
model: function () {
return App.Action.find();
}
});
App.ActionRoute = Ember.Route.extend({
events: {
submitSave: function () {
this.get("store").commit();
}
}
});
App.ActionsNewRoute = Ember.Route.extend({
renderTemplate: function () {
this.render('action');
},
model: function() {
var action = this.get('store').createRecord(App.Action);
return action;
},
events: {
submitSave: function () {
this.get("store").commit();
}
}
});
The problem is that when I first display an action, and then come back to create a new one, it looks like the template is not using the newly created record, but use instead the one displayed previously.
My interpretation is that the controller and the template are not in sync.
How would you do that?
Maybe there is a simpler way to achieve this?
Here is a JSBin with the code: http://jsbin.com/owiwak/10/edit
By saying this.render('action'), you are not just telling it to use the action template, but also the ActionController, when in fact you want the action template, but with the ActionNewController.
You need to override that:
this.render('action', {
controller: 'actions.new'
});
Updated JS Bin.